-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrtc-test.php
More file actions
1583 lines (1390 loc) · 51.8 KB
/
rtc-test.php
File metadata and controls
1583 lines (1390 loc) · 51.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: RTC Test
* Description: Load-test monitor and session capture for the WordPress RTC HTTP polling endpoint.
* Monitor: records per-request timing, CPU, query, and concurrency metrics (tagged requests).
* Capture: records real Gutenberg browser sessions as replay fixtures.
* Version: 1.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Capture CPU state as early as possible in the request lifecycle.
// getrusage() returns cumulative user+system CPU for this FPM worker process;
// we always use it as a delta (end - start) so the cumulative baseline does not
// matter. Stored in a global so rtctest_post_dispatch can compute total request
// CPU (WP bootstrap + auth + routing + dispatch) rather than dispatch-only.
//
// PHP-FPM re-executes wp-settings.php (and therefore this file) from scratch
// on every request, so this captures the start of each individual request.
$_rtctest_ru = getrusage();
$GLOBALS['rtctest_boot_cpu'] = (int) $_rtctest_ru['ru_utime.tv_sec'] * 1000000 + (int) $_rtctest_ru['ru_utime.tv_usec']
+ (int) $_rtctest_ru['ru_stime.tv_sec'] * 1000000 + (int) $_rtctest_ru['ru_stime.tv_usec'];
unset( $_rtctest_ru );
// =============================================================================
// MONITOR -- records metrics for requests tagged X-RTC-Test: 1
// =============================================================================
define( 'RTC_TEST_ENV_OPTION', 'rtc_test_env' );
define( 'RTC_TEST_CONCURRENT_OPTION', 'rtc_test_concurrent' );
define( 'RTC_TEST_DB_VERSION', '4' );
define( 'RTC_TEST_REQUEST_HEADER', 'HTTP_X_RTC_TEST' );
define( 'RTC_TEST_SCENARIO_HEADER', 'HTTP_X_RTC_SCENARIO' );
define( 'RTC_TEST_APPROACH_HEADER', 'HTTP_X_RTC_APPROACH' );
define( 'RTC_TEST_POLL_DELAY_HEADER', 'HTTP_X_RTC_POLL_DELAY' );
define( 'RTC_TEST_UPDATE_SIZE_HEADER', 'HTTP_X_RTC_UPDATE_SIZE' );
// -------------------------------------------------------------------------
// Monitor: table helpers
// -------------------------------------------------------------------------
function rtctest_log_table() {
global $wpdb;
return $wpdb->prefix . 'rtctest_log';
}
function rtctest_ensure_table() {
global $wpdb;
$table = rtctest_log_table();
// Fast path: version option matches AND the table physically exists with the
// correct schema. We spot-check columns added after the initial schema.
if ( get_option( 'rtctest_db_version' ) === RTC_TEST_DB_VERSION ) {
$col_approach = $wpdb->get_var( "SHOW COLUMNS FROM `{$table}` LIKE 'approach'" ); // phpcs:ignore
$col_delay = $wpdb->get_var( "SHOW COLUMNS FROM `{$table}` LIKE 'poll_delay'" ); // phpcs:ignore
if ( null !== $col_approach && null !== $col_delay ) {
return; // Table exists and has the current schema.
}
}
// Schema is missing or out of date. Drop and recreate so the schema is
// always correct. This table holds only test measurements — correctness of
// the schema matters more than preserving rows from an incompatible version.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange
$wpdb->query( "DROP TABLE IF EXISTS `{$table}`" ); // phpcs:ignore
delete_option( 'rtctest_db_version' );
$charset_collate = $wpdb->get_charset_collate();
// Use a direct CREATE TABLE query instead of dbDelta() to avoid dbDelta()'s
// strict SQL-formatting requirements, which can cause silent failures.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange
$wpdb->query(
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
"CREATE TABLE `{$table}` (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
ts int(11) NOT NULL DEFAULT 0,
approach varchar(60) NOT NULL DEFAULT '',
scenario varchar(100) NOT NULL DEFAULT 'unknown',
poll_delay smallint NOT NULL DEFAULT -1,
update_size varchar(20) NOT NULL DEFAULT '',
ms float NOT NULL DEFAULT 0,
total_ms float NOT NULL DEFAULT 0,
cpu_ms float NOT NULL DEFAULT 0,
total_cpu_ms float NOT NULL DEFAULT 0,
db_queries int(11) NOT NULL DEFAULT 0,
db_time_ms float NOT NULL DEFAULT 0,
memory_delta bigint(20) NOT NULL DEFAULT 0,
peak_memory bigint(20) NOT NULL DEFAULT 0,
status int(11) NOT NULL DEFAULT 200,
rooms int(11) NOT NULL DEFAULT 0,
updates_in int(11) NOT NULL DEFAULT 0,
updates_out int(11) NOT NULL DEFAULT 0,
response_bytes int(11) NOT NULL DEFAULT 0,
awareness_count int(11) NOT NULL DEFAULT 0,
should_compact tinyint(1) NOT NULL DEFAULT 0,
total_updates int(11) NOT NULL DEFAULT 0,
concurrent int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (id),
KEY approach_scenario (approach, scenario),
KEY approach_scenario_dims (approach, scenario, poll_delay, update_size),
KEY ts (ts)
) {$charset_collate}"
);
// Only mark the version current if the table was actually created.
if ( null !== $wpdb->get_var( "SHOW COLUMNS FROM `{$table}` LIKE 'poll_delay'" ) ) { // phpcs:ignore
update_option( 'rtctest_db_version', RTC_TEST_DB_VERSION, true );
} else {
error_log( '[rtctest] Failed to create table ' . $table . ': ' . $wpdb->last_error );
}
}
function rtctest_drop_table() {
global $wpdb;
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$wpdb->query( 'DROP TABLE IF EXISTS ' . rtctest_log_table() );
delete_option( 'rtctest_db_version' );
}
rtctest_ensure_table();
/**
* Poll delay from X-RTC-Poll-Delay or _rtcpolldelay. -1 = not provided.
*
* @param WP_REST_Request $request Request being handled.
* @return int Seconds between polls (as labeled by the client), or -1 if unknown.
*/
function rtctest_request_poll_delay_value( WP_REST_Request $request ) {
$raw = '';
if ( isset( $_SERVER[ RTC_TEST_POLL_DELAY_HEADER ] ) ) {
$raw = sanitize_text_field( wp_unslash( $_SERVER[ RTC_TEST_POLL_DELAY_HEADER ] ) );
} elseif ( null !== $request->get_param( '_rtcpolldelay' ) ) {
$raw = sanitize_text_field( (string) $request->get_param( '_rtcpolldelay' ) );
}
if ( '' === $raw ) {
return -1;
}
if ( is_numeric( $raw ) ) {
$v = (int) $raw;
return max( -1, min( 86400, $v ) );
}
return -1;
}
/**
* Update size label from X-RTC-Update-Size or _rtcupdatesize. Empty = not provided / N/A.
*
* @param WP_REST_Request $request Request being handled.
* @return string One of small|medium|large or ''.
*/
function rtctest_request_update_size_value( WP_REST_Request $request ) {
$raw = '';
if ( isset( $_SERVER[ RTC_TEST_UPDATE_SIZE_HEADER ] ) ) {
$raw = sanitize_text_field( wp_unslash( $_SERVER[ RTC_TEST_UPDATE_SIZE_HEADER ] ) );
} elseif ( null !== $request->get_param( '_rtcupdatesize' ) ) {
$raw = sanitize_text_field( (string) $request->get_param( '_rtcupdatesize' ) );
}
$s = strtolower( $raw );
if ( in_array( $s, array( 'small', 'medium', 'large' ), true ) ) {
return $s;
}
return '';
}
// -------------------------------------------------------------------------
// Monitor: request lifecycle hooks
// -------------------------------------------------------------------------
add_filter( 'rest_pre_dispatch', 'rtctest_pre_dispatch', 10, 3 );
add_filter( 'rest_post_dispatch', 'rtctest_post_dispatch', 10, 3 );
function rtctest_pre_dispatch( $result, $server, $request ) {
// Accept the tag from three sources, in order of reliability:
// 1. HTTP header (blocked by some reverse proxies)
// 2. PHP $_GET superglobal (never filtered by WordPress)
// 3. WP_REST_Request::get_param() (goes through WP param processing)
$tagged = isset( $_SERVER[ RTC_TEST_REQUEST_HEADER ] )
|| '1' === ( $_GET['_rtctest'] ?? '' )
|| '1' === (string) $request->get_param( '_rtctest' );
if ( ! $tagged ) {
return $result;
}
if ( false === strpos( $request->get_route(), '/wp-sync/' ) ) {
return $result;
}
global $wpdb;
$GLOBALS['rtctest_wall_start'] = microtime( true );
// Atomic concurrency increment before the query baseline snapshot.
$GLOBALS['rtctest_concurrent_at_start'] = rtctest_increment_concurrent();
register_shutdown_function( 'rtctest_decrement_concurrent' );
$GLOBALS['rtctest_queries_start'] = $wpdb->num_queries;
$GLOBALS['rtctest_dbtime_start'] = rtctest_db_time_so_far();
$GLOBALS['rtctest_memory_start'] = memory_get_usage( true );
$ru = getrusage();
$GLOBALS['rtctest_cpu_start'] = (int) $ru['ru_utime.tv_sec'] * 1000000 + (int) $ru['ru_utime.tv_usec']
+ (int) $ru['ru_stime.tv_sec'] * 1000000 + (int) $ru['ru_stime.tv_usec'];
return $result;
}
function rtctest_post_dispatch( $response, $server, $request ) {
if ( ! isset( $GLOBALS['rtctest_wall_start'] ) ) {
return $response;
}
global $wpdb;
$wall_ms = round( ( microtime( true ) - $GLOBALS['rtctest_wall_start'] ) * 1000, 2 );
$db_queries = $wpdb->num_queries - $GLOBALS['rtctest_queries_start'];
$db_time_ms = round( ( rtctest_db_time_so_far() - $GLOBALS['rtctest_dbtime_start'] ) * 1000, 2 );
$memory_delta = memory_get_usage( true ) - $GLOBALS['rtctest_memory_start'];
$ru = getrusage();
$cpu_end = (int) $ru['ru_utime.tv_sec'] * 1000000 + (int) $ru['ru_utime.tv_usec']
+ (int) $ru['ru_stime.tv_sec'] * 1000000 + (int) $ru['ru_stime.tv_usec'];
$cpu_ms = round( ( $cpu_end - $GLOBALS['rtctest_cpu_start'] ) / 1000, 2 );
$total_cpu_ms = isset( $GLOBALS['rtctest_boot_cpu'] )
? round( ( $cpu_end - $GLOBALS['rtctest_boot_cpu'] ) / 1000, 2 )
: 0.0;
$request_start = isset( $_SERVER['REQUEST_TIME_FLOAT'] ) ? (float) $_SERVER['REQUEST_TIME_FLOAT'] : 0.0;
$total_ms = $request_start > 0
? round( ( microtime( true ) - $request_start ) * 1000, 2 )
: 0.0;
$scenario = isset( $_SERVER[ RTC_TEST_SCENARIO_HEADER ] )
? sanitize_text_field( wp_unslash( $_SERVER[ RTC_TEST_SCENARIO_HEADER ] ) )
: sanitize_text_field( (string) ( $request->get_param( '_rtcscenario' ) ?? 'unknown' ) );
$approach = isset( $_SERVER[ RTC_TEST_APPROACH_HEADER ] )
? sanitize_text_field( wp_unslash( $_SERVER[ RTC_TEST_APPROACH_HEADER ] ) )
: sanitize_text_field( (string) ( $request->get_param( '_rtcapproach' ) ?? '' ) );
$poll_delay = rtctest_request_poll_delay_value( $request );
$update_size = rtctest_request_update_size_value( $request );
$data = $response->get_data();
$rooms_in = $request->get_param( 'rooms' ) ?? array();
$rooms_out = isset( $data['rooms'] ) && is_array( $data['rooms'] ) ? $data['rooms'] : array();
$updates_in = 0;
foreach ( $rooms_in as $r ) {
$updates_in += isset( $r['updates'] ) ? count( $r['updates'] ) : 0;
}
$updates_out = 0;
foreach ( $rooms_out as $r ) {
$updates_out += isset( $r['updates'] ) ? count( $r['updates'] ) : 0;
}
$first_room_out = ! empty( $rooms_out ) ? $rooms_out[0] : array();
$awareness_count = isset( $first_room_out['awareness'] ) && is_array( $first_room_out['awareness'] )
? count( $first_room_out['awareness'] )
: 0;
$should_compact = isset( $first_room_out['should_compact'] ) ? (bool) $first_room_out['should_compact'] : false;
$total_updates = isset( $first_room_out['total_updates'] ) ? (int) $first_room_out['total_updates'] : 0;
$response_bytes = strlen( wp_json_encode( $data ) );
// Build the row data and format array once so we can retry if the first
// insert fails (e.g. because the table was dropped while the db_version
// option remained set, causing rtctest_ensure_table() to skip creation).
$row_data = array(
'ts' => time(),
'approach' => $approach,
'scenario' => $scenario,
'poll_delay' => $poll_delay,
'update_size' => $update_size,
'ms' => $wall_ms,
'total_ms' => $total_ms,
'cpu_ms' => $cpu_ms,
'total_cpu_ms' => $total_cpu_ms,
'db_queries' => $db_queries,
'db_time_ms' => $db_time_ms,
'memory_delta' => $memory_delta,
'peak_memory' => memory_get_peak_usage( true ),
'status' => $response->get_status(),
'rooms' => count( $rooms_in ),
'updates_in' => $updates_in,
'updates_out' => $updates_out,
'response_bytes' => $response_bytes,
'awareness_count' => $awareness_count,
'should_compact' => $should_compact ? 1 : 0,
'total_updates' => $total_updates,
'concurrent' => $GLOBALS['rtctest_concurrent_at_start'],
);
$row_fmt = array(
'%d', '%s', '%s', '%d', '%s', '%f', '%f', '%f', '%f', '%d', '%f',
'%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d',
);
$inserted = $wpdb->insert( rtctest_log_table(), $row_data, $row_fmt );
$db_error = $wpdb->last_error;
if ( false === $inserted ) {
// Insert failed — most likely the table was dropped while the
// rtctest_db_version option remained set (so ensure_table was a no-op).
// Reset the version flag, recreate the table, and retry once.
error_log( '[rtctest] insert failed: ' . $db_error . ' — recreating table.' );
delete_option( 'rtctest_db_version' );
rtctest_ensure_table();
$inserted = $wpdb->insert( rtctest_log_table(), $row_data, $row_fmt );
$db_error = $wpdb->last_error;
if ( false === $inserted ) {
error_log( '[rtctest] insert retry failed: ' . $db_error );
}
}
// Diagnostic response headers — visible in curl -D output for debugging:
// X-RTC-Test-Active: 1 → hook executed (always set when we reach here)
// X-RTC-DB-Insert: 1 → row was written; 0 → insert failed
// X-RTC-DB-Error: … → MySQL error on insert failure (URL-encoded)
if ( $response instanceof WP_REST_Response ) {
$response->header( 'X-RTC-Test-Active', '1' );
$response->header( 'X-RTC-DB-Insert', false !== $inserted ? '1' : '0' );
if ( false === $inserted && '' !== $db_error ) {
$response->header( 'X-RTC-DB-Error', rawurlencode( substr( $db_error, 0, 300 ) ) );
}
}
unset(
$GLOBALS['rtctest_wall_start'],
$GLOBALS['rtctest_queries_start'],
$GLOBALS['rtctest_dbtime_start'],
$GLOBALS['rtctest_memory_start'],
$GLOBALS['rtctest_cpu_start'],
$GLOBALS['rtctest_concurrent_at_start']
);
return $response;
}
// -------------------------------------------------------------------------
// Monitor: concurrency counter helpers
// -------------------------------------------------------------------------
function rtctest_db_time_so_far() {
global $wpdb;
if ( ! defined( 'SAVEQUERIES' ) || ! SAVEQUERIES || ! is_array( $wpdb->queries ) ) {
return 0.0;
}
$total = 0.0;
foreach ( $wpdb->queries as $q ) {
$total += isset( $q[1] ) ? (float) $q[1] : 0.0;
}
return $total;
}
function rtctest_increment_concurrent() {
global $wpdb;
$wpdb->query(
$wpdb->prepare(
"INSERT INTO {$wpdb->options} (option_name, option_value, autoload)
VALUES (%s, '1', 'no')
ON DUPLICATE KEY UPDATE option_value = CAST(option_value AS UNSIGNED) + 1",
RTC_TEST_CONCURRENT_OPTION
)
);
return (int) $wpdb->get_var(
$wpdb->prepare(
"SELECT option_value FROM {$wpdb->options} WHERE option_name = %s",
RTC_TEST_CONCURRENT_OPTION
)
);
}
function rtctest_decrement_concurrent() {
global $wpdb;
$wpdb->query(
$wpdb->prepare(
"UPDATE {$wpdb->options}
SET option_value = GREATEST(CAST(option_value AS UNSIGNED), 1) - 1
WHERE option_name = %s",
RTC_TEST_CONCURRENT_OPTION
)
);
}
// -------------------------------------------------------------------------
// Monitor: REST endpoints (rtc-test/v1)
// -------------------------------------------------------------------------
add_action( 'rest_api_init', 'rtctest_register_routes' );
function rtctest_register_routes() {
$cap_check = static function() {
return current_user_can( 'edit_posts' );
};
register_rest_route(
'rtc-test/v1',
'/log',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => static function() {
global $wpdb;
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$rows = $wpdb->get_results(
'SELECT * FROM ' . rtctest_log_table() . ' ORDER BY id ASC',
ARRAY_A
);
foreach ( $rows as &$row ) {
$row['id'] = (int) $row['id'];
$row['ts'] = (int) $row['ts'];
$row['approach'] = (string) $row['approach'];
$row['ms'] = (float) $row['ms'];
$row['total_ms'] = (float) $row['total_ms'];
$row['cpu_ms'] = (float) $row['cpu_ms'];
$row['total_cpu_ms'] = (float) $row['total_cpu_ms'];
$row['db_queries'] = (int) $row['db_queries'];
$row['db_time_ms'] = (float) $row['db_time_ms'];
$row['memory_delta'] = (int) $row['memory_delta'];
$row['peak_memory'] = (int) $row['peak_memory'];
$row['status'] = (int) $row['status'];
$row['rooms'] = (int) $row['rooms'];
$row['updates_in'] = (int) $row['updates_in'];
$row['updates_out'] = (int) $row['updates_out'];
$row['response_bytes'] = (int) $row['response_bytes'];
$row['awareness_count'] = (int) $row['awareness_count'];
$row['should_compact'] = (bool) $row['should_compact'];
$row['total_updates'] = (int) $row['total_updates'];
$row['concurrent'] = (int) $row['concurrent'];
$row['poll_delay'] = isset( $row['poll_delay'] ) ? (int) $row['poll_delay'] : -1;
$row['update_size'] = isset( $row['update_size'] ) ? (string) $row['update_size'] : '';
}
unset( $row );
return rest_ensure_response( $rows );
},
'permission_callback' => $cap_check,
),
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => static function() {
global $wpdb;
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$wpdb->query( 'DELETE FROM ' . rtctest_log_table() );
return rest_ensure_response( array( 'cleared' => true ) );
},
'permission_callback' => $cap_check,
),
)
);
register_rest_route(
'rtc-test/v1',
'/table',
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => static function() {
rtctest_drop_table();
return rest_ensure_response( array( 'dropped' => true ) );
},
'permission_callback' => $cap_check,
)
);
register_rest_route(
'rtc-test/v1',
'/env',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'rtctest_get_env',
'permission_callback' => $cap_check,
)
);
register_rest_route(
'rtc-test/v1',
'/report',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'rtctest_rest_report',
'permission_callback' => $cap_check,
'args' => array(
'poll_delay' => array(
'required' => false,
'type' => 'integer',
),
'update_size' => array(
'required' => false,
'type' => 'string',
),
),
)
);
register_rest_route(
'rtc-test/v1',
'/report-all',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'rtctest_rest_report_all',
'permission_callback' => $cap_check,
'args' => array(
'poll_delay' => array(
'required' => false,
'type' => 'integer',
),
'update_size' => array(
'required' => false,
'type' => 'string',
),
),
)
);
register_rest_route(
'rtc-test/v1',
'/submit',
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'rtctest_rest_submit',
'permission_callback' => $cap_check,
'args' => array(
'reporter_url' => array(
'required' => true,
'type' => 'string',
'sanitize_callback' => 'esc_url_raw',
),
'api_key' => array(
'required' => true,
'type' => 'string',
'description' => 'Reporter credentials in username:password format (REPORTER_API_KEY).',
'sanitize_callback' => 'sanitize_text_field',
),
'environment_name' => array(
'required' => false,
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
),
),
)
);
}
// -------------------------------------------------------------------------
// Monitor: report helpers
// -------------------------------------------------------------------------
/**
* Load log rows for aggregate reports.
*
* @param WP_REST_Request|null $request Optional REST request with poll_delay / update_size filters.
* @param bool $with_approach When true, include approach column (report-all / submit).
* @return array<int, array<string, mixed>>
*/
function rtctest_report_fetch_rows( ?WP_REST_Request $request = null, $with_approach = false ) {
global $wpdb;
$cols = 'scenario, poll_delay, update_size, ms, total_ms, cpu_ms, total_cpu_ms, db_queries, db_time_ms,'
. ' peak_memory, updates_in, updates_out, should_compact, concurrent';
if ( $with_approach ) {
$cols = 'approach, ' . $cols;
}
$table = rtctest_log_table();
$sql = 'SELECT ' . $cols . ' FROM ' . $table . ' WHERE 1=1';
$args = array();
if ( $request instanceof WP_REST_Request ) {
if ( $request->has_param( 'poll_delay' ) ) {
$sql .= ' AND poll_delay = %d';
$args[] = (int) $request->get_param( 'poll_delay' );
}
if ( $request->has_param( 'update_size' ) ) {
$sql .= ' AND update_size = %s';
$args[] = sanitize_text_field( (string) $request->get_param( 'update_size' ) );
}
}
$sql .= ' ORDER BY id ASC';
if ( $args ) {
return $wpdb->get_results( $wpdb->prepare( $sql, $args ), ARRAY_A );
}
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
return $wpdb->get_results( $sql, ARRAY_A );
}
/**
* Aggregate log rows by scenario × poll_delay × update_size and return {"text":"..."}.
*
* Optional query params: poll_delay (int), update_size (string) restrict rows before aggregation.
*/
function rtctest_rest_report( WP_REST_Request $request ) {
$rows = rtctest_report_fetch_rows( $request, false );
if ( empty( $rows ) ) {
return rest_ensure_response( array( 'text' => '' ) );
}
// $agg[ $scenario ][ $poll_delay ][ $update_size ] = counters…
$agg = array();
foreach ( $rows as $row ) {
$scenario = (string) $row['scenario'];
$pd = isset( $row['poll_delay'] ) ? (int) $row['poll_delay'] : -1;
$sz = isset( $row['update_size'] ) ? (string) $row['update_size'] : '';
if ( ! isset( $agg[ $scenario ][ $pd ][ $sz ] ) ) {
$agg[ $scenario ][ $pd ][ $sz ] = array(
'n' => 0,
'ms_sum' => 0.0,
'ms_sq_sum' => 0.0,
'total_ms_sum' => 0.0,
'cpu_ms_sum' => 0.0,
'total_cpu_ms_sum' => 0.0,
'db_queries_sum' => 0.0,
'db_time_ms_sum' => 0.0,
'peak_memory_sum' => 0.0,
'updates_in_sum' => 0,
'updates_out_sum' => 0,
'should_compact_sum' => 0,
'max_concurrent' => 0,
);
}
$a = &$agg[ $scenario ][ $pd ][ $sz ];
$ms = (float) $row['ms'];
$a['n']++;
$a['ms_sum'] += $ms;
$a['ms_sq_sum'] += $ms * $ms;
$a['total_ms_sum'] += (float) $row['total_ms'];
$a['cpu_ms_sum'] += (float) $row['cpu_ms'];
$a['total_cpu_ms_sum'] += (float) $row['total_cpu_ms'];
$a['db_queries_sum'] += (float) $row['db_queries'];
$a['db_time_ms_sum'] += (float) $row['db_time_ms'];
$a['peak_memory_sum'] += (float) $row['peak_memory'];
$a['updates_in_sum'] += (int) $row['updates_in'];
$a['updates_out_sum'] += (int) $row['updates_out'];
$a['should_compact_sum'] += (int) $row['should_compact'];
if ( (int) $row['concurrent'] > $a['max_concurrent'] ) {
$a['max_concurrent'] = (int) $row['concurrent'];
}
unset( $a );
}
$fmt_h = "%-18s %4s %-7s %6s %8s %8s %8s %11s %8s %8s %8s %6s %6s %6s %5s %5s\n";
$fmt_r = "%-18s %4s %-7s %6d %8.1f %8.1f %8.1f %11.1f %8.1f %8.1f %8.1f %6.1f %6d %6d %5d %5d\n";
$out = sprintf( $fmt_h, 'Scenario', 'dly', 'sz', 'n', 'disp_ms', 'total_ms', 'cpu_ms', 'tot_cpu_ms', 'sd_disp', 'db_q', 'db_t_ms', 'mem_mb', 'ui_tot', 'uo_tot', 'sc', 'conc' );
$out .= sprintf( $fmt_h, '', '', '', '', 'avg', 'avg', 'avg', 'avg', 'stddev', 'avg', 'avg', 'avg', 'sum', 'sum', 'sum', 'max' );
$out .= sprintf(
$fmt_h,
str_repeat( '-', 18 ),
str_repeat( '-', 4 ),
str_repeat( '-', 7 ),
str_repeat( '-', 6 ),
str_repeat( '-', 8 ),
str_repeat( '-', 8 ),
str_repeat( '-', 8 ),
str_repeat( '-', 11 ),
str_repeat( '-', 8 ),
str_repeat( '-', 8 ),
str_repeat( '-', 8 ),
str_repeat( '-', 6 ),
str_repeat( '-', 6 ),
str_repeat( '-', 6 ),
str_repeat( '-', 5 ),
str_repeat( '-', 5 )
);
$baseline_ms_sum = 0.0;
$baseline_n = 0;
foreach ( $agg as $scenario => $by_pd ) {
if ( 'baseline' !== $scenario ) {
continue;
}
foreach ( $by_pd as $a_by_sz ) {
foreach ( $a_by_sz as $a ) {
$baseline_ms_sum += $a['ms_sum'];
$baseline_n += $a['n'];
}
}
}
$baseline_mean = $baseline_n > 0 ? $baseline_ms_sum / $baseline_n : 0.0;
foreach ( $agg as $scenario => $by_pd ) {
foreach ( $by_pd as $pd => $by_sz ) {
foreach ( $by_sz as $sz => $a ) {
$dly_label = ( $pd < 0 ) ? '-' : (string) $pd;
$sz_label = ( '' === $sz ) ? '-' : $sz;
$n = $a['n'];
$mean = $a['ms_sum'] / $n;
$var = max( 0.0, ( $a['ms_sq_sum'] / $n ) - ( $mean * $mean ) );
$scen_disp = strlen( $scenario ) > 18 ? substr( $scenario, 0, 15 ) . '...' : $scenario;
$out .= sprintf(
$fmt_r,
$scen_disp,
$dly_label,
$sz_label,
$n,
$mean,
$a['total_ms_sum'] / $n,
$a['cpu_ms_sum'] / $n,
$a['total_cpu_ms_sum'] / $n,
sqrt( $var ),
$a['db_queries_sum'] / $n,
$a['db_time_ms_sum'] / $n,
$a['peak_memory_sum'] / $n / 1048576,
$a['updates_in_sum'],
$a['updates_out_sum'],
$a['should_compact_sum'],
$a['max_concurrent']
);
}
}
}
if ( $baseline_mean > 0.0 ) {
$out .= sprintf( "\nRatio to baseline (disp_ms / baseline_disp_ms = %.1f):\n", $baseline_mean );
foreach ( $agg as $scenario => $by_pd ) {
if ( 'baseline' === $scenario ) {
continue;
}
foreach ( $by_pd as $pd => $by_sz ) {
foreach ( $by_sz as $sz => $a ) {
$n = $a['n'];
$mean = $a['ms_sum'] / $n;
$lbl = $scenario;
if ( $pd >= 0 || '' !== $sz ) {
$lbl .= sprintf( ' [%s,%s]', ( $pd < 0 ) ? '-' : (string) $pd, '' === $sz ? '-' : $sz );
}
$out .= sprintf( " %-40s %.2fx\n", $lbl, $mean / $baseline_mean );
}
}
}
}
return rest_ensure_response( array( 'text' => rtrim( $out ) ) );
}
/**
* Aggregate log rows by approach × scenario × poll_delay × update_size.
*
* Optional query params: poll_delay, update_size filter rows before aggregation.
*/
function rtctest_rest_report_all( WP_REST_Request $request ) {
$rows = rtctest_report_fetch_rows( $request, true );
if ( empty( $rows ) ) {
return rest_ensure_response( array( 'text' => '' ) );
}
$agg = array();
foreach ( $rows as $row ) {
$approach = '' !== $row['approach'] ? $row['approach'] : '(untagged)';
$scenario = (string) $row['scenario'];
$pd = isset( $row['poll_delay'] ) ? (int) $row['poll_delay'] : -1;
$sz = isset( $row['update_size'] ) ? (string) $row['update_size'] : '';
if ( ! isset( $agg[ $approach ][ $scenario ][ $pd ][ $sz ] ) ) {
$agg[ $approach ][ $scenario ][ $pd ][ $sz ] = array(
'n' => 0,
'ms_sum' => 0.0,
'ms_sq_sum' => 0.0,
'total_ms_sum' => 0.0,
'cpu_ms_sum' => 0.0,
'total_cpu_ms_sum' => 0.0,
'db_queries_sum' => 0.0,
'db_time_ms_sum' => 0.0,
'peak_memory_sum' => 0.0,
'max_concurrent' => 0,
);
}
$a = &$agg[ $approach ][ $scenario ][ $pd ][ $sz ];
$ms = (float) $row['ms'];
$a['n']++;
$a['ms_sum'] += $ms;
$a['ms_sq_sum'] += $ms * $ms;
$a['total_ms_sum'] += (float) $row['total_ms'];
$a['cpu_ms_sum'] += (float) $row['cpu_ms'];
$a['total_cpu_ms_sum'] += (float) $row['total_cpu_ms'];
$a['db_queries_sum'] += (float) $row['db_queries'];
$a['db_time_ms_sum'] += (float) $row['db_time_ms'];
$a['peak_memory_sum'] += (float) $row['peak_memory'];
if ( (int) $row['concurrent'] > $a['max_concurrent'] ) {
$a['max_concurrent'] = (int) $row['concurrent'];
}
unset( $a );
}
$fmt_h = "%-18s %4s %-7s %6s %8s %8s %8s %11s %8s %8s %8s %6s\n";
$fmt_r = "%-18s %4s %-7s %6d %8.1f %8.1f %8.1f %11.1f %8.1f %8.1f %8.1f %6d\n";
$sep_h = sprintf(
$fmt_h,
str_repeat( '-', 18 ),
str_repeat( '-', 4 ),
str_repeat( '-', 7 ),
str_repeat( '-', 6 ),
str_repeat( '-', 8 ),
str_repeat( '-', 8 ),
str_repeat( '-', 8 ),
str_repeat( '-', 11 ),
str_repeat( '-', 8 ),
str_repeat( '-', 8 ),
str_repeat( '-', 8 ),
str_repeat( '-', 6 )
);
$out = '';
foreach ( $agg as $approach => $scenarios ) {
// ASCII separators only: JSON encoders escape U+2500 as \u2500, which looks broken in clients.
$out .= sprintf( "\n--- Approach: %s ---\n", $approach );
$out .= sprintf( $fmt_h, 'Scenario', 'dly', 'sz', 'n', 'disp_ms', 'total_ms', 'cpu_ms', 'tot_cpu_ms', 'sd_disp', 'db_q', 'db_t_ms', 'conc' );
$out .= $sep_h;
$baseline_ms_sum = 0.0;
$baseline_n = 0;
if ( isset( $scenarios['baseline'] ) ) {
foreach ( $scenarios['baseline'] as $a_by_sz ) {
foreach ( $a_by_sz as $b ) {
$baseline_ms_sum += $b['ms_sum'];
$baseline_n += $b['n'];
}
}
}
$baseline_mean = $baseline_n > 0 ? $baseline_ms_sum / $baseline_n : 0.0;
foreach ( $scenarios as $scenario => $by_pd ) {
foreach ( $by_pd as $pd => $by_sz ) {
foreach ( $by_sz as $sz => $a ) {
$dly_label = ( $pd < 0 ) ? '-' : (string) $pd;
$sz_label = ( '' === $sz ) ? '-' : $sz;
$n = $a['n'];
$mean = $a['ms_sum'] / $n;
$var = max( 0.0, ( $a['ms_sq_sum'] / $n ) - ( $mean * $mean ) );
$scen_disp = strlen( $scenario ) > 18 ? substr( $scenario, 0, 15 ) . '...' : $scenario;
$out .= sprintf(
$fmt_r,
$scen_disp,
$dly_label,
$sz_label,
$n,
$mean,
$a['total_ms_sum'] / $n,
$a['cpu_ms_sum'] / $n,
$a['total_cpu_ms_sum'] / $n,
sqrt( $var ),
$a['db_queries_sum'] / $n,
$a['db_time_ms_sum'] / $n,
$a['max_concurrent']
);
}
}
}
if ( $baseline_mean > 0.0 ) {
$out .= "\n Ratio to baseline (disp_ms):\n";
foreach ( $scenarios as $scenario => $by_pd ) {
if ( 'baseline' === $scenario ) {
continue;
}
foreach ( $by_pd as $pd => $by_sz ) {
foreach ( $by_sz as $sz => $a ) {
$mean = $a['ms_sum'] / $a['n'];
$lbl = $scenario;
if ( $pd >= 0 || '' !== $sz ) {
$lbl .= sprintf( ' [%s,%s]', ( $pd < 0 ) ? '-' : (string) $pd, '' === $sz ? '-' : $sz );
}
$out .= sprintf( " %-40s %.2fx\n", $lbl, $mean / $baseline_mean );
}
}
}
}
}
return rest_ensure_response( array( 'text' => ltrim( $out ) ) );
}
function rtctest_detect_object_cache_type() {
global $wp_object_cache;
// WP's built-in non-persistent in-memory cache.
if ( ! wp_using_ext_object_cache() ) {
return 'default';
}
if ( ! isset( $wp_object_cache ) || ! is_object( $wp_object_cache ) ) {
return 'ext:unknown';
}
// Redis Object Cache (rhubarbgroup/redis-cache by Till Krüss).
// The drop-in exposes redis_status() whether or not the plugin is active.
if ( method_exists( $wp_object_cache, 'redis_status' ) ) {
return $wp_object_cache->redis_status() ? 'redis' : 'redis-disconnected';
}
// Object Cache Pro (commercial Redis drop-in).
if ( str_contains( strtolower( get_class( $wp_object_cache ) ), 'redis' ) ) {
return 'redis';
}
// WP Redis (Pantheon / Human Made / 10up). Different drop-in, same backend.
// Uses a $redis property but no redis_status() method.
if ( defined( 'WP_REDIS_OBJECT_CACHE' )
|| ( property_exists( $wp_object_cache, 'redis' ) && isset( $wp_object_cache->redis ) ) ) {
return 'redis';
}
// Memcached drop-in (Automattic / WordPress.com style).
// Exposes a public $mc property holding the actual client instance.
if ( property_exists( $wp_object_cache, 'mc' ) && isset( $wp_object_cache->mc ) ) {
if ( $wp_object_cache->mc instanceof \Memcached ) {
return 'memcached';
}
if ( $wp_object_cache->mc instanceof \Memcache ) {
return 'memcache';
}
}
// LiteSpeed Cache.
if ( strpos( get_class( $wp_object_cache ), 'LiteSpeed' ) !== false ) {
return 'litespeed';
}
// W3 Total Cache.
if ( method_exists( $wp_object_cache, '_get_engine' )
|| strpos( get_class( $wp_object_cache ), 'W3TC' ) !== false ) {
return 'w3-total-cache';
}
// APCu drop-in.
if ( method_exists( $wp_object_cache, 'apcu_fetch' )
|| strpos( get_class( $wp_object_cache ), 'APCu' ) !== false ) {
return 'apcu';
}
// Fall back to the actual class name — captures everything else.
return 'ext:' . get_class( $wp_object_cache );
}
function rtctest_get_env() {
global $wpdb;
$compaction_threshold = class_exists( 'WP_HTTP_Polling_Sync_Server' )
? WP_HTTP_Polling_Sync_Server::COMPACTION_THRESHOLD
: null;
$awareness_timeout_s = class_exists( 'WP_HTTP_Polling_Sync_Server' )
? WP_HTTP_Polling_Sync_Server::AWARENESS_TIMEOUT
: null;
$env = array(
'php_version' => PHP_VERSION,
'wp_version' => get_bloginfo( 'version' ),
'mysql_version' => $wpdb->db_version(),
'ext_object_cache' => wp_using_ext_object_cache(),
'object_cache_type' => rtctest_detect_object_cache_type(),
'savequeries' => defined( 'SAVEQUERIES' ) && SAVEQUERIES,
'compaction_threshold' => $compaction_threshold,
'awareness_timeout_s' => $awareness_timeout_s,
'captured_at' => time(),
);
update_option( RTC_TEST_ENV_OPTION, $env, false );
return rest_ensure_response( $env );
}
function rtctest_rest_submit( WP_REST_Request $request ) {
$reporter_url = $request->get_param( 'reporter_url' );
$api_key = $request->get_param( 'api_key' ); // username:password format
$environment_name = $request->get_param( 'environment_name' ) ?: get_option( 'siteurl' );
if ( 'https' !== wp_parse_url( $reporter_url, PHP_URL_SCHEME ) ) {
return new WP_Error( 'insecure_url', 'reporter_url must use HTTPS to protect credentials.', array( 'status' => 400 ) );
}
// Build environment snapshot.
$env = rtctest_get_env()->get_data();
$rows = rtctest_report_fetch_rows( null, true );
if ( empty( $rows ) ) {
return new WP_Error( 'no_data', 'No log entries to submit.', array( 'status' => 400 ) );
}
// Aggregate by approach × scenario × poll_delay × update_size.
$agg = array();
foreach ( $rows as $row ) {
$approach = '' !== $row['approach'] ? $row['approach'] : 'untagged';
$scenario = (string) $row['scenario'];
$pd = isset( $row['poll_delay'] ) ? (int) $row['poll_delay'] : -1;
$sz = isset( $row['update_size'] ) ? (string) $row['update_size'] : '';
if ( ! isset( $agg[ $approach ][ $scenario ][ $pd ][ $sz ] ) ) {
$agg[ $approach ][ $scenario ][ $pd ][ $sz ] = array(
'n' => 0,
'ms_sum' => 0.0,
'ms_sq_sum' => 0.0,