the descriptionFilter value the generators accept. * * @var array */ public const GAP_FILTERS = array( 'description' => 'without_full', 'short_description' => 'without_short', 'tags' => 'without_tags', 'seo_meta' => 'without_seo_meta', 'faq' => 'without_faq', ); /** @var bool */ private static $invalidated_this_request = false; /** @var callable */ private $clock; public function __construct( ?callable $clock = null ) { $this->clock = $clock ?? static function (): float { return microtime( true ); }; } /** * Returns the scan. A complete fresh scan is served as it is. * * Without one, the last complete scan is served with `refreshing` set while * one background event counts again, so a large catalog is not counted * inside the request. The request counts by itself when nothing complete * is stored (the first run), when the last complete scan was cheap (its * numbers then stay exact right after a write), when the caller asks for a * count now (the merchant's Count again) or when WP-Cron cannot run the * event. A count in the request resumes a cached partial scan, so repeated * requests converge on a complete scan. While a failed background count is * remembered, the last complete scan is served as stale. * * @param bool $count_now Count in this request unless a complete fresh scan is stored. * @return array|\WP_Error Payload per the catalog-scan contract, or an error. A failure is never cached. */ public function get_scan( bool $count_now = false ) { $cached = get_transient( self::CACHE_KEY ); if ( $this->is_valid_payload( $cached ) && empty( $cached['partial'] ) ) { return $this->present( $cached, false, false ); } $last_good = get_transient( self::LAST_GOOD_KEY ); $last_good = $this->is_valid_payload( $last_good ) && empty( $last_good['partial'] ) ? $last_good : null; if ( ! $count_now && null !== $last_good ) { if ( false !== get_transient( self::FAILED_KEY ) ) { return $this->present( $last_good, true, false ); } if ( ! $this->is_cheap( $last_good ) && BackgroundRefresh::QUEUED === BackgroundRefresh::request( self::REFRESH_HOOK ) ) { return $this->present( $last_good, false, true ); } } $fresh = $this->count( $this->resumable( $cached ), (float) apply_filters( 'aipt_catalog_scan_budget_seconds', self::DEFAULT_BUDGET_SECONDS ) ); if ( is_array( $fresh ) || null === $last_good ) { return $fresh; } return $this->present( $last_good, true, false ); } /** * The background count, run by the refresh event: a longer time budget than * a request, resuming a partial scan. A scan still partial queues the next * run, so the background finishes it. A complete fresh scan stored since the * event was queued is kept. * * @return array|\WP_Error Payload per the catalog-scan contract, or the error of a failed count. */ public function refresh_in_background() { $cached = get_transient( self::CACHE_KEY ); if ( $this->is_valid_payload( $cached ) && empty( $cached['partial'] ) ) { return $this->present( $cached, false, false ); } $fresh = $this->count( $this->resumable( $cached ), self::BACKGROUND_BUDGET_SECONDS ); if ( is_array( $fresh ) && $fresh['partial'] ) { BackgroundRefresh::request( self::REFRESH_HOOK ); } return $fresh; } /** * Count, and store a scan that worked: the fresh cache, and the stale * fallback when it is complete. A count that worked also forgets a failed * background count, so the next view stops calling the counts stale. * * @param array|null $resume A cached partial scan to complete. * @param float $budget Seconds after which the remaining gaps are left for the next run. * @return array|\WP_Error */ private function count( ?array $resume, float $budget ) { self::$invalidated_this_request = false; $fresh = $this->compute( $resume, $budget ); if ( is_array( $fresh ) ) { set_transient( self::CACHE_KEY, $fresh, $fresh['partial'] ? self::PARTIAL_TTL : self::FRESH_TTL ); if ( ! $fresh['partial'] ) { set_transient( self::LAST_GOOD_KEY, $fresh, WEEK_IN_SECONDS ); } if ( false !== get_transient( self::FAILED_KEY ) ) { delete_transient( self::FAILED_KEY ); } } return $fresh; } /** * A complete stored scan as the catalog-scan contract sends it. * * @param array $scan Complete stored scan. * @param bool $stale A new count failed, so this is the last one that worked. * @param bool $refreshing It may be out of date; a background count is on its way. * @return array */ private function present( array $scan, bool $stale, bool $refreshing ): array { $scan['skipped'] = array(); $scan['stale'] = $stale; $scan['refreshing'] = $refreshing; return $scan; } /** * A cached partial scan a count can complete, or null. * * @param mixed $cached Value read back from the fresh cache. * @return array|null */ private function resumable( $cached ): ?array { return $this->is_valid_payload( $cached ) && ! empty( $cached['partial'] ) && isset( $cached['skipped'] ) && is_array( $cached['skipped'] ) ? $cached : null; } /** * The last complete scan took at most CHEAP_SCAN_SECONDS. A scan stored * before its time was kept counts as expensive. * * @param array $scan Complete stored scan. * @return bool */ private function is_cheap( array $scan ): bool { return isset( $scan['seconds'] ) && is_numeric( $scan['seconds'] ) && (float) $scan['seconds'] <= self::CHEAP_SCAN_SECONDS; } /** * Returns the best scan that is already stored, and never computes or queries the catalog. * * Order: a complete fresh scan, then the last complete scan, then a partial scan. * A scan older than CACHED_MAX_AGE is not served. * * @return array|null Payload per the catalog-scan contract, or null when nothing usable is stored. */ public function get_cached_scan(): ?array { $fresh = get_transient( self::CACHE_KEY ); $last_good = get_transient( self::LAST_GOOD_KEY ); if ( $this->is_servable( $fresh ) && empty( $fresh['partial'] ) ) { return $this->present( $fresh, false, false ); } if ( $this->is_servable( $last_good ) && empty( $last_good['partial'] ) ) { return $this->present( $last_good, true, false ); } if ( $this->is_servable( $fresh ) ) { $fresh['stale'] = false; $fresh['refreshing'] = false; return $fresh; } return null; } /** * @param mixed $payload Value read back from a transient. */ private function is_servable( $payload ): bool { if ( ! $this->is_valid_payload( $payload ) || ! is_array( $payload['gaps'] ) ) { return false; } $scanned_at = strtotime( (string) $payload['scannedAt'] ); return false !== $scanned_at && time() - $scanned_at <= self::CACHED_MAX_AGE; } /** * Runs the counts. Returns an error when any count query fails. * * Every run counts at least one gap that has no count yet, even when the total * already used up the budget, so a slow catalog still makes progress. A gap that * is not counted because the budget ran out is listed in `skipped`; a gap that * cannot be counted at all (no supported SEO plugin) stays null and is not. * * `seconds` adds up the time every run of the scan spent counting, so a * resumed scan knows what the whole count cost. * * @param array|null $resume A cached partial payload to complete: its total and counts are reused and only its skipped gaps are counted. * @param float $budget Seconds after which the remaining gaps are skipped. * @return array|\WP_Error */ private function compute( ?array $resume, float $budget ) { $started = (float) call_user_func( $this->clock ); $gaps = array_fill_keys( array_keys( self::GAP_FILTERS ), null ); if ( null === $resume ) { $total = ( new ProductFilterBuilder() )->countProducts(); $pending = self::GAP_FILTERS; } else { $total = (int) $resume['total']; $pending = array_intersect_key( self::GAP_FILTERS, array_flip( $resume['skipped'] ) ); foreach ( array_diff_key( self::GAP_FILTERS, $pending ) as $gap => $filter ) { $gaps[ $gap ] = isset( $resume['gaps'][ $gap ] ) ? (int) $resume['gaps'][ $gap ] : null; } } if ( null === $total ) { return $this->failure(); } $seo_plugin = SeoPluginDetector::detect(); $skipped = array(); $counted = 0; foreach ( $pending as $gap => $filter ) { if ( 'seo_meta' === $gap && null === SeoPluginDetector::get_description_gap_source() ) { continue; } $elapsed = (float) call_user_func( $this->clock ) - $started; if ( $counted > 0 && $elapsed > $budget ) { $skipped[] = $gap; continue; } $count = ( new ProductFilterBuilder() )->contentFilters( array( $filter ) )->countProducts(); if ( null === $count ) { return $this->failure(); } $gaps[ $gap ] = $count; ++$counted; } $earlier = null !== $resume && isset( $resume['seconds'] ) && is_numeric( $resume['seconds'] ) ? (float) $resume['seconds'] : 0.0; return array( 'total' => $total, 'gaps' => $gaps, 'skipped' => $skipped, 'seoPlugin' => null === $seo_plugin ? null : array( 'slug' => (string) $seo_plugin['plugin_slug'], 'name' => (string) $seo_plugin['plugin_name'], ), 'scannedAt' => gmdate( 'Y-m-d\TH:i:s\Z' ), 'stale' => false, 'refreshing' => false, 'partial' => array() !== $skipped, 'seconds' => round( $earlier + (float) call_user_func( $this->clock ) - $started, 3 ), ); } private function failure(): \WP_Error { return new \WP_Error( self::ERROR_CODE, __( 'The catalog scan could not be completed. Please try again.', 'ai-product-tools' ), array( 'status' => 500 ) ); } /** * @param mixed $payload Value read back from a transient. */ private function is_valid_payload( $payload ): bool { return is_array( $payload ) && isset( $payload['total'], $payload['gaps'], $payload['scannedAt'] ); } /** * Drops the fresh cache so the next request rescans. The last good scan stays as the stale fallback. */ public static function invalidate(): void { if ( self::$invalidated_this_request ) { return; } delete_transient( self::CACHE_KEY ); self::$invalidated_this_request = true; } /** * Invalidates on product writes and on every input the counts read. Safe to call more than once. */ public static function register_invalidation_hooks(): void { if ( has_action( 'save_post_product', array( __CLASS__, 'invalidate' ) ) ) { return; } add_action( 'save_post_product', array( __CLASS__, 'invalidate' ) ); add_action( 'trashed_post', array( __CLASS__, 'on_post_changed' ) ); add_action( 'untrashed_post', array( __CLASS__, 'on_post_changed' ) ); add_action( 'deleted_post', array( __CLASS__, 'invalidate' ) ); add_action( 'added_post_meta', array( __CLASS__, 'on_meta_changed' ), 10, 3 ); add_action( 'updated_post_meta', array( __CLASS__, 'on_meta_changed' ), 10, 3 ); add_action( 'deleted_post_meta', array( __CLASS__, 'on_meta_changed' ), 10, 3 ); add_action( 'set_object_terms', array( __CLASS__, 'on_terms_changed' ), 10, 4 ); add_action( 'deleted_term_relationships', array( __CLASS__, 'on_relationships_deleted' ), 10, 3 ); add_action( 'activated_plugin', array( __CLASS__, 'invalidate' ) ); add_action( 'deactivated_plugin', array( __CLASS__, 'invalidate' ) ); add_action( 'aipt_product_filter_cache_flushed', array( __CLASS__, 'invalidate' ) ); } /** * Trash and restore: only products matter. * * @param int $post_id Post that was trashed or restored. */ public static function on_post_changed( $post_id ): void { if ( 'product' === get_post_type( (int) $post_id ) ) { self::invalidate(); } } /** * @param mixed $meta_id Meta row id or ids. * @param int $object_id Post id. * @param string $meta_key Meta key. */ public static function on_meta_changed( $meta_id, $object_id, $meta_key ): void { if ( in_array( $meta_key, self::watched_meta_keys(), true ) ) { self::invalidate(); } } /** * @param int $object_id Post id. * @param mixed $terms Terms as passed to wp_set_object_terms(). * @param mixed $tt_ids Term taxonomy ids. * @param string $taxonomy Taxonomy name. */ public static function on_terms_changed( $object_id, $terms = null, $tt_ids = null, $taxonomy = '' ): void { if ( 'product_tag' === $taxonomy ) { self::invalidate(); } } /** * @param int $object_id Post id. * @param mixed $tt_ids Term taxonomy ids. * @param string $taxonomy Taxonomy name. */ public static function on_relationships_deleted( $object_id, $tt_ids = null, $taxonomy = '' ): void { if ( 'product_tag' === $taxonomy ) { self::invalidate(); } } /** * @return string[] */ private static function watched_meta_keys(): array { return array_merge( array( '_aipt_faq_data' ), SeoPluginDetector::get_description_meta_keys() ); } }