0 ? $window_seconds : 0 ); } $key = 'aipt_rate_limit_' . self::SCOPE . '_' . $user_id; $outcome = AtomicRateLimiter::consumeUnits( $key, $units, $max_requests, $window_seconds ); if ( null !== $outcome ) { return $outcome['allowed'] ? null : self::error( $outcome['reset_in'] ); } return self::consumeViaTransient( $key, $units, $max_requests, $window_seconds ); } /** * The fixed-window transient algorithm this class used before the shared * counters table. Only reached when $wpdb cannot run the atomic queries * (a test harness); it keeps a read-then-write gap that a real request * never takes. * * @param string $key Transient key. * @param int $units Units this call is worth. * @param int $max_requests Window budget. * @param int $window_seconds Window length. * @return WP_Error|null */ private static function consumeViaTransient( string $key, int $units, int $max_requests, int $window_seconds ): ?WP_Error { $data = get_transient( $key ); $now = time(); if ( false === $data || ! is_array( $data ) ) { return self::startWindow( $key, $units, $max_requests, $window_seconds, $now ); } $elapsed = $now - (int) ( $data['window_start'] ?? 0 ); if ( $elapsed >= $window_seconds ) { return self::startWindow( $key, $units, $max_requests, $window_seconds, $now ); } $remaining_window = $window_seconds - $elapsed; $current_count = (int) ( $data['count'] ?? 0 ); if ( $current_count + $units > $max_requests ) { return self::error( $remaining_window ); } set_transient( $key, array( 'count' => $current_count + $units, 'window_start' => (int) ( $data['window_start'] ?? $now ) ), $remaining_window ); return null; } /** * Start (or restart, once the previous window elapsed) a fresh window * holding $units, when it fits within one window's budget on its own. * * @param string $key Transient key. * @param int $units Units this call is worth. * @param int $max_requests Window budget. * @param int $window_seconds Window length. * @param int $now Current Unix timestamp. * @return WP_Error|null */ private static function startWindow( string $key, int $units, int $max_requests, int $window_seconds, int $now ): ?WP_Error { if ( $units > $max_requests ) { return self::error( $window_seconds ); } set_transient( $key, array( 'count' => $units, 'window_start' => $now ), $window_seconds ); return null; } /** * @param int $wait_seconds Seconds until the caller may retry. * @return WP_Error The same `rate_limit_exceeded` (429) shape `StaticRateLimitTrait::rateLimitErrorStatic()` returns. */ private static function error( int $wait_seconds ): WP_Error { return new WP_Error( 'rate_limit_exceeded', sprintf( /* translators: %d: seconds to wait before retrying. */ __( 'Rate limit exceeded. Please wait %d seconds before trying again.', 'ai-product-tools' ), $wait_seconds ), array( 'status' => 429, 'retry_after' => $wait_seconds ) ); } }