prefix . 'aipt_rate_limit_counters'; } /** * Atomically increment $bucket_key's counter for the current fixed * window and report whether this request is still within * $max_requests. * * A request past the limit still increments the stored counter (it is * cheaper, and behaviorally identical, to let it keep counting rather * than branch around the write) exactly as the equivalent chatbot * mechanism does, so the returned count is "requests seen", not * "requests admitted". * * `remaining` and `reset_in` are both exact for a request in a FRESH * window; `reset_in` on a request that falls inside an existing window * but is still under the limit is an upper bound (the full window * length) rather than the precise remainder, since nothing currently * reads that value except on denial, where it is always exact (a * dedicated read recovers the real window bounds). * * @param string $bucket_key Unique, already-namespaced bucket identifier (max 191 bytes). * @param int $max_requests Maximum requests allowed per window. * @param int $window_seconds Window duration in seconds. * @return array{allowed:bool,remaining:int,reset_in:int} */ public static function checkAndIncrement( string $bucket_key, int $max_requests, int $window_seconds ): array { if ( $max_requests < 1 || $window_seconds < 1 ) { return array( 'allowed' => false, 'remaining' => 0, 'reset_in' => 0 ); } $count = self::tryAtomicIncrement( $bucket_key, $window_seconds ); if ( null === $count ) { return self::checkAndIncrementViaTransient( $bucket_key, $max_requests, $window_seconds ); } if ( $count <= 0 ) { return array( 'allowed' => false, 'remaining' => 0, 'reset_in' => max( 1, $window_seconds ) ); } if ( $count > $max_requests ) { return array( 'allowed' => false, 'remaining' => 0, 'reset_in' => self::remainingWindowSeconds( $bucket_key, $window_seconds ), ); } return array( 'allowed' => true, 'remaining' => max( 0, $max_requests - $count ), 'reset_in' => $window_seconds, ); } /** * Atomically consume $units of $bucket_key's budget for the current fixed * window, all or nothing: the request is admitted only when the whole * amount still fits, and a denied request consumes nothing. * * Admission is one conditional UPDATE whose WHERE clause holds both the * "window is live" and the "still fits" test, so the storage engine's * row lock serializes concurrent callers and none is ever admitted past * $max_requests. Only when that UPDATE changes no row (no row yet, an * expired window, or a full one) does the cold path start a fresh window * and retry it once. * * @param string $bucket_key Unique, already-namespaced bucket identifier (max 191 bytes). * @param int $units Units this request is worth (minimum 1). * @param int $max_requests Units allowed per window. * @param int $window_seconds Window duration in seconds. * @return array{allowed:bool,reset_in:int}|null Null when $wpdb cannot run these * queries at all (only a test harness), so the caller can fall back. */ public static function consumeUnits( string $bucket_key, int $units, int $max_requests, int $window_seconds ): ?array { if ( $max_requests < 1 || $window_seconds < 1 ) { return array( 'allowed' => false, 'reset_in' => max( 0, $window_seconds ) ); } $units = max( 1, $units ); if ( $units > $max_requests ) { return array( 'allowed' => false, 'reset_in' => $window_seconds ); } $admitted = self::addUnitsToLiveWindow( $bucket_key, $units, $max_requests ); if ( null === $admitted ) { return null; } if ( 0 === $admitted ) { self::startWindowIfExpired( $bucket_key, $window_seconds ); $admitted = self::addUnitsToLiveWindow( $bucket_key, $units, $max_requests ); } if ( 1 === $admitted ) { return array( 'allowed' => true, 'reset_in' => $window_seconds ); } if ( false === $admitted ) { return array( 'allowed' => false, 'reset_in' => $window_seconds ); } $reset_in = self::liveWindowSecondsLeft( $bucket_key ); if ( null === $reset_in ) { return null; } return array( 'allowed' => false, 'reset_in' => $reset_in ); } /** * Give back $units that {@see consumeUnits()} took from $bucket_key's * live window, for a request that turned out to start no work at all. * Only a live window is touched (an ended one already starts over at * zero), and the counter never goes below zero. * * @param string $bucket_key Bucket identifier. * @param int $units Units to give back (minimum 1). * @return bool Whether the database accepted the write. */ public static function releaseUnits( string $bucket_key, int $units ): bool { global $wpdb; $units = max( 1, $units ); try { $table = self::table(); $result = $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET counter = GREATEST( counter - %d, 0 ) WHERE bucket_key = %s AND window_start + window_seconds > UNIX_TIMESTAMP()", $units, $bucket_key ) ); } catch ( \Throwable $e ) { return false; } return false !== $result; } /** * Seconds left in $bucket_key's window, read back from its row. * * @param string $bucket_key Bucket identifier. * @return int|null At least 1, or null when the row cannot be read. */ private static function liveWindowSecondsLeft( string $bucket_key ): ?int { global $wpdb; try { $table = self::table(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT window_start, window_seconds FROM {$table} WHERE bucket_key = %s", $bucket_key ) ); } catch ( \Throwable $e ) { return null; } if ( ! is_object( $row ) || ! isset( $row->window_start, $row->window_seconds ) ) { return null; } return max( 1, ( (int) $row->window_start + (int) $row->window_seconds ) - time() ); } /** * Add $units to $bucket_key's live window when they still fit. * * @param string $bucket_key Bucket identifier. * @param int $units Units to add. * @param int $max_requests Units allowed per window. * @return int|false|null Rows changed (1 admitted, 0 not), false on a database * error, null when $wpdb cannot run the query at all. */ private static function addUnitsToLiveWindow( string $bucket_key, int $units, int $max_requests ) { global $wpdb; try { $table = self::table(); $result = $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET counter = counter + %d WHERE bucket_key = %s AND window_start + window_seconds > UNIX_TIMESTAMP() AND counter + %d <= %d", $units, $bucket_key, $units, $max_requests ) ); } catch ( \Throwable $e ) { return null; } if ( false === $result ) { return false; } return is_int( $result ) ? min( 1, $result ) : null; } /** * Start a fresh window for $bucket_key when its row is missing or its * window has ended. Each statement touches one row atomically; when * concurrent callers race here, the first one starts the window and the * others' statements change nothing. * * @param string $bucket_key Bucket identifier. * @param int $window_seconds Window duration in seconds. * @return void */ private static function startWindowIfExpired( string $bucket_key, int $window_seconds ): void { global $wpdb; $table = self::table(); $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET counter = 0, window_start = UNIX_TIMESTAMP(), window_seconds = %d WHERE bucket_key = %s AND window_start + window_seconds <= UNIX_TIMESTAMP()", $window_seconds, $bucket_key ) ); $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$table} (bucket_key, counter, window_start, window_seconds) VALUES (%s, 0, UNIX_TIMESTAMP(), %d)", $bucket_key, $window_seconds ) ); } /** * Issue the single atomic write and report the post-increment counter. * * @param string $bucket_key Bucket identifier. * @param int $window_seconds Window duration in seconds. * @return int|null The post-increment counter (0 on a genuine write * failure), or null when $wpdb cannot run this query at all. */ private static function tryAtomicIncrement( string $bucket_key, int $window_seconds ): ?int { global $wpdb; try { $table = self::table(); $write_result = $wpdb->query( $wpdb->prepare( "INSERT INTO {$table} (bucket_key, counter, window_start, window_seconds) VALUES (%s, LAST_INSERT_ID(1), UNIX_TIMESTAMP(), %d) ON DUPLICATE KEY UPDATE counter = LAST_INSERT_ID(IF(window_start + window_seconds > UNIX_TIMESTAMP(), counter + 1, 1)), window_start = IF(window_start + window_seconds > UNIX_TIMESTAMP(), window_start, UNIX_TIMESTAMP()), window_seconds = VALUES(window_seconds)", $bucket_key, $window_seconds ) ); if ( false === $write_result ) { return 0; } $count = (int) $wpdb->insert_id; } catch ( \Throwable $e ) { return null; } return $count > 0 ? $count : null; } /** * Cold path, only reached on denial: the real seconds left in * $bucket_key's current window, read back from the row this request's * own write just touched. * * @param string $bucket_key Bucket identifier. * @param int $window_seconds Configured window length, used as the fallback when the row cannot be read back. * @return int */ private static function remainingWindowSeconds( string $bucket_key, int $window_seconds ): int { global $wpdb; try { $table = self::table(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT window_start, window_seconds FROM {$table} WHERE bucket_key = %s", $bucket_key ) ); } catch ( \Throwable $e ) { return max( 1, $window_seconds ); } if ( null === $row ) { return max( 1, $window_seconds ); } $remaining = ( (int) $row->window_start + (int) $row->window_seconds ) - time(); return max( 1, $remaining ); } /** * The original fixed-window algorithm this class replaces for everyday * use: a plain get/set-transient pair. Kept only as the fallback above; * every real request goes through the atomic path and never reaches * this method; it still carries the same narrow TOCTOU gap between its * read and its write, acceptable here only because nothing in a real * deployment ever takes this branch. * * @param string $bucket_key Transient key (reused verbatim as the transient name). * @param int $max_requests Maximum requests allowed per window. * @param int $window_seconds Window duration in seconds. * @return array{allowed:bool,remaining:int,reset_in:int} */ private static function checkAndIncrementViaTransient( string $bucket_key, int $max_requests, int $window_seconds ): array { $rate_data = get_transient( $bucket_key ); if ( false === $rate_data || ! is_array( $rate_data ) ) { set_transient( $bucket_key, array( 'count' => 1, 'window_start' => time() ), $window_seconds ); return array( 'allowed' => true, 'remaining' => $max_requests - 1, 'reset_in' => $window_seconds ); } $elapsed = time() - (int) $rate_data['window_start']; if ( $elapsed >= $window_seconds ) { set_transient( $bucket_key, array( 'count' => 1, 'window_start' => time() ), $window_seconds ); return array( 'allowed' => true, 'remaining' => $max_requests - 1, 'reset_in' => $window_seconds ); } if ( (int) $rate_data['count'] >= $max_requests ) { return array( 'allowed' => false, 'remaining' => 0, 'reset_in' => $window_seconds - $elapsed ); } $rate_data['count']++; set_transient( $bucket_key, $rate_data, $window_seconds - $elapsed ); return array( 'allowed' => true, 'remaining' => $max_requests - (int) $rate_data['count'], 'reset_in' => $window_seconds - $elapsed ); } }