Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 99 additions & 5 deletions includes/Framework/Utilities/BackgroundJobHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ abstract class BackgroundJobHandler extends AsyncRequest {
/** @var string debug message, used by the system status tool */
protected $debug_message;

/** @var string transient key for caching queue empty status */
protected $queue_empty_cache_key;

/** @var string transient key for caching sync in progress status */
protected $sync_in_progress_cache_key;


/**
* Initiate new background job handler
Expand All @@ -66,8 +72,10 @@ abstract class BackgroundJobHandler extends AsyncRequest {
*/
public function __construct() {
parent::__construct();
$this->cron_hook_identifier = $this->identifier . '_cron';
$this->cron_interval_identifier = $this->identifier . '_cron_interval';
$this->cron_hook_identifier = $this->identifier . '_cron';
$this->cron_interval_identifier = $this->identifier . '_cron_interval';
$this->queue_empty_cache_key = $this->identifier . '_queue_empty';
$this->sync_in_progress_cache_key = $this->identifier . '_sync_in_progress';
$this->add_hooks();
}

Expand Down Expand Up @@ -165,10 +173,26 @@ public function maybe_handle() {
/**
* Check whether job queue is empty or not
*
* Uses transient caching to avoid expensive database queries on every request.
* The cache is invalidated when jobs are created, updated, or completed.
*
* @since 4.4.0
* @return bool True if queue is empty, false otherwise
*/
protected function is_queue_empty() {
// Skip expensive query on frontend - only needed in admin/ajax/cron/process contexts.
// The method runs if ANY of these is true: is_admin(), wp_doing_ajax(), wp_doing_cron(), or is_process_request().
// On pure frontend requests (none of those conditions), we return true to skip the expensive query.
if ( ! is_admin() && ! wp_doing_ajax() && ! wp_doing_cron() && ! $this->is_process_request() ) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so the only case where the method should run is:
if it's an admin user, making an ajax call, through cron?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the is_process_request method? I cannot find the implementation of it

return true; // Assume empty on frontend to avoid query
}

// Check cache first
$cached = get_transient( $this->queue_empty_cache_key );
if ( false !== $cached ) {
return 'empty' === $cached;
}

global $wpdb;

$key = $this->identifier . '_job_%';
Expand All @@ -189,7 +213,41 @@ protected function is_queue_empty() {
)
);

return intval( $count ) === 0;
$is_empty = intval( $count ) === 0;

// Cache the result for 1 hour as a safety net - it will be invalidated when job status changes
set_transient( $this->queue_empty_cache_key, $is_empty ? 'empty' : 'not_empty', HOUR_IN_SECONDS );

return $is_empty;
}

/**
* Invalidate the queue empty cache.
*
* Should be called when job status changes (create, update, complete, fail, delete).
*
* @since 3.5.0
*/
protected function invalidate_queue_cache() {
delete_transient( $this->queue_empty_cache_key );
delete_transient( $this->sync_in_progress_cache_key );
// Also clear the is_sync_in_progress cache used by Sync class
delete_transient( 'wc_facebook_sync_in_progress' );
}


/**
* Check whether the current request is a background process request.
*
* Checks if the request action matches this handler's identifier,
* indicating it's an actual background processing request.
*
* @since 3.5.0
* @return bool True if this is a background process request, false otherwise
*/
protected function is_process_request() {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verified in maybe_handle()
return isset( $_REQUEST['action'] ) && $_REQUEST['action'] === $this->identifier;
}


Expand Down Expand Up @@ -396,6 +454,9 @@ public function create_job( $attrs ) {
]
);

// Invalidate cache since a new job was created
$this->invalidate_queue_cache();

$job = new \stdClass();

foreach ( $attrs as $key => $value ) {
Expand Down Expand Up @@ -480,6 +541,9 @@ public function get_job( $id = null ) {
/**
* Gets jobs.
*
* Uses transient caching for common queries (like checking for processing jobs)
* to avoid expensive database queries on every request.
*
* @since 4.4.2
*
* @param array $args {
Expand All @@ -488,6 +552,7 @@ public function get_job( $id = null ) {
* @type string|array $status Job status(es) to include
* @type string $order ASC or DESC. Defaults to DESC
* @type string $orderby Field to order by. Defaults to option_id
* @type bool $use_cache Whether to use caching. Defaults to true.
* }
* @return \stdClass[]|object[]|null Found jobs or null if none found
*/
Expand All @@ -502,6 +567,13 @@ public function get_jobs( $args = [] ) {
]
);

// Skip expensive query on frontend - only needed in admin/ajax/cron contexts.
// The method runs if ANY of these is true: is_admin(), wp_doing_ajax(), or wp_doing_cron().
// On pure frontend requests (none of those conditions), we return null to skip the expensive query.
if ( ! is_admin() && ! wp_doing_ajax() && ! wp_doing_cron() ) {
return null; // Return no jobs on frontend to avoid query
}

$replacements = [ $this->identifier . '_job_%' ];
$status_query = '';

Expand Down Expand Up @@ -615,7 +687,8 @@ public function process_job( $job, $items_per_batch = null ) {
$job->status = 'processing';
$job->started_processing_at = current_time( 'mysql' );

$job = $this->update_job( $job );
// Invalidate cache when status changes to processing
$job = $this->update_job( $job, true );
}

$data_key = $this->data_key;
Expand Down Expand Up @@ -684,9 +757,11 @@ public function process_job( $job, $items_per_batch = null ) {
* @since 4.4.0
*
* @param \stdClass|object|string $job Job instance or ID
* @param bool $invalidate_cache Whether to invalidate the queue cache. Defaults to false
* to avoid cache thrashing during progress updates.
* @return \stdClass|object|false on failure
*/
public function update_job( $job ) {
public function update_job( $job, $invalidate_cache = false ) {
if ( is_string( $job ) ) {
$job = $this->get_job( $job );
}
Expand All @@ -695,6 +770,13 @@ public function update_job( $job ) {
}
$job->updated_at = current_time( 'mysql' );
$this->update_job_option( $job );

// Only invalidate cache when explicitly requested (e.g., status changes)
// to avoid cache thrashing during frequent progress updates
if ( $invalidate_cache ) {
$this->invalidate_queue_cache();
}

/**
* Runs when a job is updated.
*
Expand Down Expand Up @@ -725,6 +807,10 @@ public function complete_job( $job ) {
$job->status = 'completed';
$job->completed_at = current_time( 'mysql' );
$this->update_job_option( $job );

// Invalidate cache since job status changed
$this->invalidate_queue_cache();

/**
* Runs when a job is completed.
*
Expand Down Expand Up @@ -763,6 +849,10 @@ public function fail_job( $job, $reason = '' ) {
$job->failure_reason = $reason;
}
$this->update_job_option( $job );

// Invalidate cache since job status changed
$this->invalidate_queue_cache();

/**
* Runs when a job is failed.
*
Expand Down Expand Up @@ -792,6 +882,10 @@ public function delete_job( $job ) {
return false;
}
$wpdb->delete( $wpdb->options, [ 'option_name' => "{$this->identifier}_job_{$job->id}" ] );

// Invalidate cache since a job was deleted
$this->invalidate_queue_cache();

/**
* Runs after a job is deleted.
*
Expand Down
23 changes: 22 additions & 1 deletion includes/Products/Sync.php
Original file line number Diff line number Diff line change
Expand Up @@ -254,18 +254,39 @@ private function get_product_index( $product_id ) {
/**
* Determines whether a sync is currently in progress.
*
* This method uses caching to avoid expensive database queries.
* The cache is automatically invalidated when jobs are created, updated, or completed.
* On frontend requests, this always returns false to avoid expensive queries.
*
* @since 2.0.0
*
* @return bool
*/
public static function is_sync_in_progress() {
// On frontend, skip the check entirely - visitors don't need sync status
if ( ! is_admin() && ! wp_doing_ajax() && ! wp_doing_cron() ) {
return false;
}

// Check cache first
$cache_key = 'wc_facebook_sync_in_progress';
$cached = get_transient( $cache_key );
if ( false !== $cached ) {
return 'yes' === $cached;
}

// Query for processing jobs
$jobs = facebook_for_woocommerce()->get_products_sync_background_handler()->get_jobs(
array(
'status' => 'processing',
)
);

return ! empty( $jobs );
$in_progress = ! empty( $jobs );

// Cache the result - invalidated when job status changes
set_transient( $cache_key, $in_progress ? 'yes' : 'no', 0 );

return $in_progress;
}
}
3 changes: 2 additions & 1 deletion includes/Products/Sync/Background.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ public function process_job( $job, $items_per_batch = null ) {
$job->status = 'processing';
$job->started_processing_at = current_time( 'mysql' );

$job = $this->update_job( $job );
// Invalidate cache when status changes to processing
$job = $this->update_job( $job, true );
}

$data_key = $this->data_key;
Expand Down
8 changes: 7 additions & 1 deletion includes/Utilities/DebugTools.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,13 @@ public function add_debug_tool( $tools ) {
public function clean_up_old_background_sync_options() {
global $wpdb;

$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '%wc_facebook_background_product_sync%'" );
// Delete job entries (but not cache transients which use different pattern)
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE 'wc_facebook_background_product_sync_job_%'" );

// Invalidate all sync-related caches since we deleted jobs directly from the database
delete_transient( 'wc_facebook_background_product_sync_queue_empty' );
delete_transient( 'wc_facebook_background_product_sync_sync_in_progress' );
delete_transient( 'wc_facebook_sync_in_progress' );

return __( 'Background sync jobs have been deleted.', 'facebook-for-woocommerce' );
}
Expand Down
Loading
Loading