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:
2026-09-27 16:33:16 +08:00
parent b187c1c4d3
commit 22b46ad175
2 changed files with 29 additions and 11 deletions
+15 -4
View File
@@ -377,7 +377,11 @@ class RestApiTest extends TestCase {
$this->assertSame( 'too_many_requests', $response->get_data()['code'] );
}
public function test_post_view_429_increments_rate_limit_stats(): void {
/**
* Blocked requests are counted 1 in 10 (each sample adds 10), so anonymous
* traffic cannot turn every blocked request into an option write.
*/
public function test_post_view_429_samples_rate_limit_stats(): void {
$GLOBALS['_wp_post_types'][40] = 'hp_listing';
$_COOKIE['wpdo_view_40'] = '1'; // Trigger cookie block.
$nonce = wp_create_nonce( 'wp_rest' );
@@ -385,10 +389,17 @@ class RestApiTest extends TestCase {
$req = new WP_REST_Request( 'POST', '/wpdo/v1/listings/40/view' );
$req->set_param( 'id', 40 );
$req->set_header( 'X-WP-Nonce', $nonce );
$this->api->post_view( $req );
$writes = 0;
for ( $i = 0; $i < 200; $i++ ) {
$before = get_option( 'wpdo_rl_stats', [] );
$this->assertSame( 429, $this->api->post_view( $req )->get_status() );
$writes += get_option( 'wpdo_rl_stats', [] ) === $before ? 0 : 1;
}
$stats = get_option( 'wpdo_rl_stats', [] );
$this->assertSame( 1, (int) ( $stats['40'] ?? 0 ) );
$count = (int) ( get_option( 'wpdo_rl_stats', [] )['40'] ?? 0 );
$this->assertSame( 10 * $writes, $count, 'each sample adds 10' );
$this->assertGreaterThan( 0, $writes );
$this->assertLessThan( 60, $writes, 'about 20 writes for 200 blocked requests, not 200' );
}
// ── get_status: rate_limit_stats ─────────────────────────────────────────