= PHP_INT_MAX; } /** * Run $create only while the active-connection count is below the cap, * the whole check-then-create sequence serialized by a site-wide mutex. * * @param callable $create Creates the new connection/credential and returns * its result array, or a WP_Error on its own failure. * Runs only while a slot is confirmed free. * @return array|WP_Error $create's own result, a plan-denial * WP_Error at the cap (fail closed when the active count cannot be * read), or a busy WP_Error when the mutex could not be acquired in time. */ public static function withSlot( callable $create ) { $lock_value = self::generateLockValue(); if ( ! self::acquireLock( $lock_value ) ) { return new WP_Error( 'aipt_mcp_busy', __( 'The MCP server is busy right now. Please try again in a moment.', 'ai-product-tools' ), array( 'status' => 503 ) ); } try { $limit = self::limit(); $active = ( new ConnectionStore() )->countActive(); if ( null === $active || $active >= $limit ) { return PlanDenial::error( 'mcp_connections', PlanDenial::PLAN_BUSINESS, __( 'The free plan includes up to 5 connected agents. The Business plan also covers unlimited connections.', 'ai-product-tools' ), 'aipt_mcp_connection_limit_reached', array( 'limit' => $limit, 'active' => null === $active ? 0 : $active, ) ); } return $create(); } finally { self::releaseLock( $lock_value ); } } /** * Override the wait timing for tests only, so a blocked/stale-lock test * does not have to run in real time. A production no-op. * * @internal PHPUnit use only. * @param int|null $max_wait_ms Total wait budget, or null to restore the default. * @param int|null $step_ms Poll interval, or null to restore the default. * @return void */ public static function setTimingForTesting( ?int $max_wait_ms, ?int $step_ms ): void { if ( ! self::isTestEnvironment() ) { return; } self::$maxWaitMsOverride = $max_wait_ms; self::$stepMsOverride = $step_ms; } /** * Acquire the mutex, waiting and retrying until it is won or the budget * runs out. * * @param string $value This caller's unique lock value. * @return bool */ private static function acquireLock( string $value ): bool { global $wpdb; $max_wait_ms = self::$maxWaitMsOverride ?? self::DEFAULT_MAX_WAIT_MS; $step_ms = self::$stepMsOverride ?? self::DEFAULT_STEP_MS; $deadline = microtime( true ) + ( $max_wait_ms / 1000 ); do { $inserted = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %s, 'off')", self::LOCK_OPTION_NAME, $value ) ); if ( 1 === (int) $inserted ) { return true; } self::reapStaleLock(); if ( microtime( true ) >= $deadline ) { return false; } usleep( max( 1000, $step_ms * 1000 ) ); } while ( true ); } /** * Delete the lock row only if its value is older than * {@see STALE_AFTER_SECONDS}, via a compare-and-delete on the exact value * read, so a lock refreshed by its real owner between the read and the * delete is never removed out from under it. * * @return void */ private static function reapStaleLock(): void { global $wpdb; $current = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", self::LOCK_OPTION_NAME ) ); if ( ! is_string( $current ) || '' === $current ) { return; } $held_since = (int) strtok( $current, ':' ); if ( $held_since <= 0 || ( time() - $held_since ) < self::STALE_AFTER_SECONDS ) { return; } $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s AND option_value = %s", self::LOCK_OPTION_NAME, $current ) ); } /** * Release the mutex, but only if it still holds exactly the value this * call acquired — never another caller's lock, and never through the * options API. * * @param string $value This caller's unique lock value. * @return void */ private static function releaseLock( string $value ): void { global $wpdb; $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s AND option_value = %s", self::LOCK_OPTION_NAME, $value ) ); } /** * A unique value for one lock hold: ":". * * @return string */ private static function generateLockValue(): string { return time() . ':' . bin2hex( random_bytes( 8 ) ); } }