60, 'display' => 'Every minute (FoldRocket)', ); return $schedules; } ); if ( ! wp_next_scheduled( self::CRON_HOOK ) ) { wp_schedule_event( time() + 60, 'frkt_every_minute', self::CRON_HOOK ); } } public function dispatch( int $job_id, int $delay = 0 ): void { if ( function_exists( 'as_has_scheduled_action' ) && as_has_scheduled_action( self::AS_HOOK, array( $job_id ), 'frkt' ) ) { $this->nudge_action_scheduler_from_rest(); return; } if ( $delay > 0 && function_exists( 'as_schedule_single_action' ) ) { as_schedule_single_action( time() + $delay, self::AS_HOOK, array( $job_id ), 'frkt' ); return; } if ( function_exists( 'as_enqueue_async_action' ) ) { as_enqueue_async_action( self::AS_HOOK, array( $job_id ), 'frkt' ); $this->nudge_action_scheduler_from_rest(); return; } // Durable fallback for sites where Action Scheduler cannot initialize. if ( ! wp_next_scheduled( self::CRON_HOOK ) ) { wp_schedule_single_event( time() + 1, self::CRON_HOOK ); } } /** * Action Scheduler only auto-dispatches its async runner on admin shutdown. * Jobs queued through REST would otherwise wait for its minute cron tick. */ private function nudge_action_scheduler_from_rest(): void { if ( ! defined( 'REST_REQUEST' ) || ! REST_REQUEST ) { return; } if ( ! class_exists( \ActionScheduler::class ) || ! class_exists( \ActionScheduler_AsyncRequest_QueueRunner::class ) ) { return; } $store = \ActionScheduler::store(); if ( ! $store instanceof \ActionScheduler_Store ) { return; } // This sends a non-blocking loopback request; heavy work never runs in REST. ( new \ActionScheduler_AsyncRequest_QueueRunner( $store ) )->maybe_dispatch(); } public function process_queue(): void { $started = microtime( true ); $result = array( 'ran' => false, 'pending' => 0 ); do { $result = $this->run_next(); } while ( $result['ran'] && $result['pending'] > 0 && microtime( true ) - $started < 15 ); if ( $result['pending'] > 0 && ! wp_next_scheduled( self::CRON_HOOK ) ) { wp_schedule_single_event( time() + 5, self::CRON_HOOK ); } } /** * Claim and execute one open job. Per-resource locks allow independent * attachments to progress concurrently while serializing conflicting work. * * @return array{ran: bool, locked: bool, job: array|null, pending: int} */ public function run_next( ?int $actor = null ): array { $repo = new JobRepository(); $executed = null; $locked = false; // Never batch multiple heavy jobs in one REST or cron request. foreach ( $repo->claim_pending( 1, $actor ) as $job ) { $lease_token = (string) ( $job['leaseToken'] ?? '' ); $resource_lock = $this->resource_lock_name( $job ); $lock_token = $this->acquire_named_lock( $resource_lock, self::RESOURCE_LOCK_TTL ); if ( null === $lock_token ) { $repo->release_claim( (int) $job['id'], $lease_token, 5 ); $locked = true; continue; } try { $this->execute( $job, $resource_lock, $lock_token ); $executed = $repo->find( (int) $job['id'] ); } finally { $this->release_named_lock( $resource_lock, $lock_token ); } } return array( 'ran' => null !== $executed, 'locked' => $locked, 'job' => $executed, 'pending' => $repo->count_open( $actor ), ); } public function run_job( int $job_id ): void { $repo = new JobRepository(); $job = $repo->claim_one( $job_id ); if ( ! $job ) { return; } $lease_token = (string) ( $job['leaseToken'] ?? '' ); $resource_lock = $this->resource_lock_name( $job ); $lock_token = $this->acquire_named_lock( $resource_lock, self::RESOURCE_LOCK_TTL ); if ( null === $lock_token ) { $repo->release_claim( $job_id, $lease_token, 5 ); $this->dispatch( $job_id, 5 ); return; } try { $this->execute( $job, $resource_lock, $lock_token ); } finally { $this->release_named_lock( $resource_lock, $lock_token ); } } /** @param array $job */ private function resource_lock_name( array $job ): string { $attachment_id = (int) ( $job['attachmentId'] ?? $job['payload']['attachment_id'] ?? 0 ); if ( 'build_library_zip' === (string) ( $job['type'] ?? '' ) ) { $resource = 'zip-user:' . (int) ( $job['requestedBy'] ?? $job['payload']['requested_by'] ?? 0 ); } else { $resource = $attachment_id > 0 ? 'attachment:' . $attachment_id : 'type:' . (string) ( $job['type'] ?? 'unknown' ); } return 'frkt_job_resource_' . md5( TableNames::site_id() . ':' . $resource ); } private function acquire_named_lock( string $option, int $ttl ): ?string { $now = time(); $token = wp_generate_uuid4(); $value = (string) wp_json_encode( array( 'token' => $token, 'acquired_at' => $now ) ); if ( add_option( $option, $value, '', 'no' ) ) { return $token; } $held_raw = get_option( $option, '' ); $held = is_string( $held_raw ) ? json_decode( $held_raw, true ) : null; $held_since = is_array( $held ) ? (int) ( $held['acquired_at'] ?? 0 ) : 0; if ( $held_since > 0 && ( $now - $held_since ) < $ttl ) { return null; } if ( ! is_string( $held_raw ) || ! $this->compare_and_delete_option( $option, $held_raw ) ) { return null; } return add_option( $option, $value, '', 'no' ) ? $token : null; } private function release_named_lock( string $option, string $token ): void { $held_raw = get_option( $option, '' ); $held = is_string( $held_raw ) ? json_decode( $held_raw, true ) : null; if ( is_string( $held_raw ) && is_array( $held ) && hash_equals( (string) ( $held['token'] ?? '' ), $token ) ) { $this->compare_and_delete_option( $option, $held_raw ); } } private function renew_named_lock( string $option, string $token ): bool { $held_raw = get_option( $option, '' ); $held = is_string( $held_raw ) ? json_decode( $held_raw, true ) : null; if ( ! is_string( $held_raw ) || ! is_array( $held ) || ! hash_equals( (string) ( $held['token'] ?? '' ), $token ) ) { return false; } $next = (string) wp_json_encode( array( 'token' => $token, 'acquired_at' => time() ) ); if ( $next === $held_raw ) { return true; } return $this->compare_and_swap_option( $option, $held_raw, $next ); } private function compare_and_delete_option( string $option, string $expected ): bool { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Atomic compare-and-delete cannot be expressed through the Options API. $deleted = $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE option_name = %s AND option_value = %s', $wpdb->options, $option, $expected ) ); wp_cache_delete( $option, 'options' ); return 1 === (int) $deleted; } private function compare_and_swap_option( string $option, string $expected, string $next ): bool { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Atomic compare-and-swap cannot be expressed through the Options API. $updated = $wpdb->query( $wpdb->prepare( 'UPDATE %i SET option_value = %s WHERE option_name = %s AND option_value = %s', $wpdb->options, $next, $option, $expected ) ); wp_cache_delete( $option, 'options' ); return 1 === (int) $updated; } /** * @param array $job */ private function execute( array $job, string $resource_lock, string $lock_token ): void { if ( function_exists( 'set_time_limit' ) ) { // Cap below Local's 1200s default so a hung provider cannot wedge PHP-FPM forever. @set_time_limit( 90 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, Squiz.PHP.DiscouragedFunctions.Discouraged } // Browser-driven runs must finish even if the tab closes or the client times out. ignore_user_abort( true ); $repo = new JobRepository(); $job_id = (int) $job['id']; $payload = is_array( $job['payload'] ?? null ) ? $job['payload'] : array(); $type = (string) ( $job['type'] ?? '' ); $lease_token = (string) ( $job['leaseToken'] ?? '' ); if ( ! $repo->heartbeat( $job_id, $lease_token ) || ! $this->renew_named_lock( $resource_lock, $lock_token ) ) { return; } $previous_user = get_current_user_id(); $requested_by = (int) ( $job['requestedBy'] ?? $payload['requested_by'] ?? 0 ); try { $this->assert_job_authorized( $type, $payload, $requested_by ); if ( $requested_by > 0 && $requested_by !== $previous_user ) { wp_set_current_user( $requested_by ); } if ( 'build_library_zip' === $type ) { $next = ( new LibraryZipService() )->step( $payload ); if ( $repo->checkpoint( $job_id, $next['payload'], $next['progress'], $next['done'], $lease_token ) && ! $next['done'] ) { $this->dispatch( $job_id ); } return; } if ( isset( $payload['kind'] ) && in_array( $type, array( 'rebuild_index', 'rebuild_references', 'scan_duplicates' ), true ) ) { $next = ( new \FoldRocket\Application\Services\LibraryScanService() )->step( $job_id, $payload ); $done = ! empty( $next['done'] ); if ( $repo->checkpoint( $job_id, $next, \FoldRocket\Application\Services\LibraryScanService::progress( $next ), $done, $lease_token ) && ! $done ) { $this->dispatch( $job_id ); } return; } match ( $type ) { 'index_asset' => ( new AssetIndexer() )->index_now( (int) ( $payload['attachment_id'] ?? 0 ) ), 'analyze_asset' => $this->call_handler( AssetAnalyzer::class, static fn() => ( new AssetAnalyzer() )->analyze( (int) ( $payload['attachment_id'] ?? 0 ) ) ), 'generate_metadata' => $this->call_handler( AssetAnalyzer::class, fn() => $this->run_generate_metadata( $payload ) ), 'scan_references' => $this->call_handler( \FoldRocket\Application\Services\ReferenceScannerService::class, static fn() => ( new \FoldRocket\Application\Services\ReferenceScannerService() )->scan_attachment( (int) ( $payload['attachment_id'] ?? 0 ), false ) ), 'scan_duplicates' => $this->call_handler( DuplicateDetector::class, static fn() => ( new DuplicateDetector() )->scan() ), 'optimize_asset' => $this->call_handler( OptimizationService::class, static fn() => ( new OptimizationService() )->optimize( (int) ( $payload['attachment_id'] ?? 0 ), true, (int) ( $payload['quality'] ?? OptimizationService::QUALITY_DEFAULT ) ) ), 'convert_asset' => $this->call_handler( ImageConvertService::class, static function () use ( $payload ) { if ( ! \FoldRocket\Domain\Features\FeatureRegistry::is_available( 'format_convert' ) ) { throw new \RuntimeException( __( 'Format conversion is no longer available.', 'foldrocket' ), 403 ); } return ( new ImageConvertService() )->convert( (int) ( $payload['attachment_id'] ?? 0 ), array( 'confirmed' => true, 'format' => (string) ( $payload['format'] ?? '' ), 'quality' => (int) ( $payload['quality'] ?? ImageConvertService::QUALITY_DEFAULT ), 'backup' => true, ) ); } ), 'ai_edit_image' => $this->call_handler( \FoldRocket\Commercial\AI\AiImageEditService::class, static fn() => ( new \FoldRocket\Commercial\AI\AiImageEditService() )->run_generation( $job_id, $payload ) ), 'apply_ai_edit' => $this->call_handler( \FoldRocket\Commercial\AI\AiImageEditService::class, static fn() => ( new \FoldRocket\Commercial\AI\AiImageEditService() )->run_apply( $job_id, $payload ) ), 'optimize_video' => $this->call_handler( VideoOptimizerService::class, static fn() => ( new VideoOptimizerService() )->process( $job_id, $payload, $lease_token ) ), 'restore_video' => $this->call_handler( VideoOptimizerService::class, static fn() => ( new VideoOptimizerService() )->restore( $job_id, $payload, $lease_token ) ), 'generate_video_poster' => $this->call_handler( VideoOptimizerService::class, static fn() => ( new VideoOptimizerService() )->generate_poster( $job_id, $payload, $lease_token ) ), // Semantic search disabled — complete pending jobs without calling providers. 'generate_embedding' => array( 'skipped' => true, 'reason' => 'semantic_search_disabled' ), default => throw new \RuntimeException( 'Unknown job type: ' . $type ), }; // Respect cancel requested while this worker was busy. $fresh = $repo->find( $job_id ); if ( $fresh && (string) ( $fresh['status'] ?? '' ) === 'cancelled' ) { return; } if ( $this->renew_named_lock( $resource_lock, $lock_token ) ) { $repo->mark_completed( $job_id, $lease_token ); } } catch ( \Throwable $e ) { $fresh = $repo->find( $job_id ); if ( ! $fresh || $fresh['status'] === 'cancelled' ) { return; } $code = (int) $e->getCode(); $permanent = $e instanceof \InvalidArgumentException || ( $code >= 400 && $code < 500 && ! in_array( $code, array( 408, 429 ), true ) ); $retryable = ! $permanent && (int) $job['attempts'] < ( isset( $payload['kind'] ) ? 3 : 5 ); if ( 'build_library_zip' === $type && ! $retryable ) { ( new LibraryZipService() )->cleanup_job( $payload ); } if ( in_array( $type, array( 'analyze_asset', 'generate_metadata' ), true ) ) { $attachment_id = (int) ( $payload['attachment_id'] ?? 0 ); if ( $attachment_id > 0 ) { ( new \FoldRocket\Domain\Assets\AssetRepository() )->upsert( $attachment_id, array( 'ai_status' => $retryable ? 'analyzing' : 'failed' ) ); } } if ( 'convert_asset' === $type ) { $attachment_id = (int) ( $payload['attachment_id'] ?? 0 ); $file = $attachment_id > 0 ? get_attached_file( $attachment_id ) : ''; if ( $attachment_id > 0 && ( ! is_string( $file ) || $file === '' || ! is_readable( $file ) ) ) { update_post_meta( $attachment_id, \FoldRocket\Application\Services\AssetIndexer::MISSING_FILE_META, '1' ); } } $failed = $repo->mark_failed( $job_id, $lease_token, $e->getMessage(), $retryable ); if ( $failed && $retryable ) { $this->dispatch( $job_id, JobRepository::retry_delay( (int) $job['attempts'] ) ); } } finally { if ( get_current_user_id() !== $previous_user ) { wp_set_current_user( $previous_user ); } } } /** @param array $payload */ private function assert_job_authorized( string $type, array $payload, int $user_id ): void { if ( in_array( $type, array( 'index_asset', 'generate_embedding' ), true ) ) { return; } if ( $user_id < 1 || ! get_userdata( $user_id ) ) { throw new \RuntimeException( __( 'The user who requested this job is no longer available.', 'foldrocket' ), 403 ); } $attachment_id = (int) ( $payload['attachment_id'] ?? 0 ); $attachment_jobs = array( 'analyze_asset', 'generate_metadata', 'scan_references', 'optimize_asset', 'convert_asset', 'ai_edit_image', 'apply_ai_edit', 'optimize_video', 'restore_video', 'generate_video_poster' ); if ( in_array( $type, $attachment_jobs, true ) && ( $attachment_id < 1 || ! user_can( $user_id, 'edit_post', $attachment_id ) ) ) { throw new \RuntimeException( __( 'You can no longer edit the media item for this job.', 'foldrocket' ), 403 ); } $features = array( 'analyze_asset' => 'ai_analysis', 'generate_metadata' => 'ai_metadata', 'scan_references' => 'usage_detection', 'optimize_asset' => 'optimize', 'convert_asset' => 'format_convert', 'ai_edit_image' => 'ai_image_edit', 'apply_ai_edit' => 'ai_image_edit', 'optimize_video' => 'video_optimizer', 'restore_video' => 'video_optimizer', 'generate_video_poster' => 'video_poster', 'build_library_zip' => 'download_zip', ); $feature = $features[ $type ] ?? null; if ( is_string( $feature ) && ! FeatureRegistry::is_available( $feature ) ) { throw new \RuntimeException( __( 'This feature is no longer available for the queued job.', 'foldrocket' ), 403 ); } if ( in_array( $type, array( 'analyze_asset', 'generate_metadata', 'ai_edit_image', 'apply_ai_edit' ), true ) && ! user_can( $user_id, 'frkt_run_ai' ) && ! user_can( $user_id, 'frkt_run_ai' ) && ! user_can( $user_id, 'manage_options' ) ) { throw new \RuntimeException( __( 'You can no longer run AI jobs.', 'foldrocket' ), 403 ); } if ( in_array( $type, array( 'rebuild_index', 'rebuild_references', 'scan_duplicates' ), true ) && ! user_can( $user_id, 'frkt_manage_library' ) && ! user_can( $user_id, 'frkt_manage_library' ) && ! user_can( $user_id, 'upload_files' ) ) { throw new \RuntimeException( __( 'You can no longer manage the media library.', 'foldrocket' ), 403 ); } } /** * @param class-string $class */ private function call_handler( string $class, callable $run ): mixed { if ( ! class_exists( $class ) ) { throw new \RuntimeException( 'Job handler is not available in this package.' ); } return $run(); } /** * @param array $payload */ private function run_generate_metadata( array $payload ): void { $attachment_id = (int) ( $payload['attachment_id'] ?? 0 ); $field = (string) ( $payload['field'] ?? 'all' ); $locale = isset( $payload['locale'] ) && is_string( $payload['locale'] ) && $payload['locale'] !== '' ? $payload['locale'] : null; $analyzer = new AssetAnalyzer(); if ( isset( $payload['fields'] ) && is_array( $payload['fields'] ) ) { $analyzer->suggest_selected_fields( $attachment_id, $payload['fields'] ); return; } if ( 'all' === $field ) { $analyzer->suggest_all_fields( $attachment_id, $locale, true === ( $payload['regenerate_filename'] ?? false ), true === ( $payload['translate_all'] ?? true ) ); return; } $analyzer->suggest_field( $attachment_id, $field, $locale, true === ( $payload['translate_all'] ?? false ) ); } }