= self::SLOW_MS || $memFraction >= self::MEM_LIMIT ) { return max( self::MIN, (int) floor( $size / 2 ) ); } if ( $chunkMs < self::FAST_MS ) { return min( self::MAX, $size + max( 5, (int) floor( $size / 4 ) ) ); } return $size; } /** * Size for the next chunk of a job; applies the measurements collected since the last call. * * @param int $jobId Job. * @param int $cap Upper bound from the engine. * @return int */ public static function next( int $jobId, int $cap ): int { $state = JobRowsRepo::getSentinel( $jobId, 'tuner' ); $size = (int) ( $state['size'] ?? self::START ); $items = JobRowsRepo::counter( $jobId, 'tuner_items' ); if ( $items > 0 ) { $ms = (float) JobRowsRepo::counter( $jobId, 'tuner_ms' ); $peak = JobRowsRepo::counter( $jobId, 'tuner_peak' ); $size = self::adjust( $size, $ms, self::memoryFraction( $peak ) ); JobRowsRepo::sentinel( $jobId, 'tuner', array( 'size' => $size, 'last_ms' => $ms, 'last_items' => $items, 'peak_memory' => $peak, ) ); self::resetCounters( $jobId ); } if ( function_exists( 'memory_reset_peak_usage' ) ) { memory_reset_peak_usage(); // The rows of the chunk built now measure their own peak. } return max( self::MIN, min( $cap, $size ) ); } /** * Add the time of one processed row and raise the memory mark of the chunk, in one statement. * * @param int $jobId Job. * @param float $ms Milliseconds. * @return void */ public static function observe( int $jobId, float $ms ): void { global $wpdb; $memory = function_exists( 'memory_reset_peak_usage' ) ? memory_get_peak_usage( true ) : memory_get_usage( true ); $now = gmdate( 'Y-m-d H:i:s' ); $wpdb->query( $wpdb->prepare( "INSERT INTO %i (job_id, row_no, byte_offset, status, code, created_at) VALUES (%d, 0, %d, 'job', 'tuner_ms', %s), (%d, 0, 1, 'job', 'tuner_items', %s), (%d, 0, %d, 'job', 'tuner_peak', %s) ON DUPLICATE KEY UPDATE byte_offset = IF(code = 'tuner_peak', GREATEST(byte_offset, VALUES(byte_offset)), byte_offset + VALUES(byte_offset))", \Rotosix\CatalogRelay\Lifecycle\Schema::table(), $jobId, (int) round( $ms ), $now, $jobId, $now, $jobId, $memory, $now ) ); } /** * Zero the per-chunk counters. * * @param int $jobId Job. * @return void */ private static function resetCounters( int $jobId ): void { global $wpdb; $wpdb->query( $wpdb->prepare( "UPDATE %i SET byte_offset = 0 WHERE job_id = %d AND row_no = 0 AND status = 'job' AND code IN ('tuner_ms', 'tuner_items', 'tuner_peak')", \Rotosix\CatalogRelay\Lifecycle\Schema::table(), $jobId ) ); } /** * Peak memory of a chunk as a fraction of the memory limit PHP enforces, the ceiling of the engine's memory guard (a * WP_MEMORY_LIMIT above a memory_limit the host locked lower is never reached). * * @param int $peak Bytes. * @return float */ public static function memoryFraction( int $peak ): float { $ceiling = MemoryGuard::ceiling(); return $ceiling > 0 ? $peak / $ceiling : 0.0; // memory_limit = -1 (typical for WP-CLI): no ceiling. } }