perf(2meet-data-optimizer): stop writing an option for every rate-limited view
- blocked POST /listings/{id}/view requests update wpdo_rl_stats 1 in 10,
each sample adding 10: anonymous traffic no longer turns 1:1 into DB writes,
and the admin top list stays representative (unbiased estimate)
- Verify: RestApiTest counts option writes (about 20 for 200 blocked requests),
unit 698, integration 577, phpcs, stan
- PR: PR-094
This commit is contained in:
@@ -23,6 +23,9 @@ if ( ! defined( 'ABSPATH' ) ) {
|
||||
*/
|
||||
class TMDO_REST_API {
|
||||
|
||||
/** Blocked views are counted 1 in this many (wpdo_rl_stats). */
|
||||
private const RL_STATS_SAMPLE = 10;
|
||||
|
||||
const NAMESPACE = 'wpdo/v1';
|
||||
|
||||
/**
|
||||
@@ -725,14 +728,18 @@ class TMDO_REST_API {
|
||||
|
||||
if ( $cookie_blocked || $ip_blocked ) {
|
||||
// Track rate-limit hits per post for admin visibility, capped at 100 entries.
|
||||
$rl_stats = get_option( 'wpdo_rl_stats', array() );
|
||||
$rl_stats[ (string) $post_id ] = ( (int) ( $rl_stats[ (string) $post_id ] ?? 0 ) ) + 1;
|
||||
if ( count( $rl_stats ) > 100 ) {
|
||||
// Keep only the top-100 posts by hit count to bound option size.
|
||||
arsort( $rl_stats );
|
||||
$rl_stats = array_slice( $rl_stats, 0, 100, true );
|
||||
// Sampled (1 in RL_STATS_SAMPLE, each sample adding RL_STATS_SAMPLE) so
|
||||
// anonymous requests cannot turn every blocked view into an option write.
|
||||
if ( 1 === wp_rand( 1, self::RL_STATS_SAMPLE ) ) {
|
||||
$rl_stats = get_option( 'wpdo_rl_stats', array() );
|
||||
$rl_stats[ (string) $post_id ] = ( (int) ( $rl_stats[ (string) $post_id ] ?? 0 ) ) + self::RL_STATS_SAMPLE;
|
||||
if ( count( $rl_stats ) > 100 ) {
|
||||
// Keep only the top-100 posts by hit count to bound option size.
|
||||
arsort( $rl_stats );
|
||||
$rl_stats = array_slice( $rl_stats, 0, 100, true );
|
||||
}
|
||||
update_option( 'wpdo_rl_stats', $rl_stats, false );
|
||||
}
|
||||
update_option( 'wpdo_rl_stats', $rl_stats, false );
|
||||
|
||||
return new WP_REST_Response(
|
||||
array(
|
||||
|
||||
Reference in New Issue
Block a user