Repository navigation
Expand file tree
/
Copy pathclass-wp-agent-option-run-control-store.php
More file actions
654 lines (585 loc) · 24.2 KB
/
Copy pathclass-wp-agent-option-run-control-store.php
File metadata and controls
654 lines (585 loc) · 24.2 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
<?php
/**
* Option-backed run-control store.
*
* @package AgentsAPI
*/
namespace AgentsAPI\AI;
use AgentsAPI\Core\Workspace\WP_Agent_Workspace_Scope;
defined( 'ABSPATH' ) || exit;
if ( ! interface_exists( WP_Agent_Atomic_Workspace_Run_Control_Store::class ) ) {
require_once __DIR__ . '/interface-wp-agent-atomic-workspace-run-control-store.php';
}
if ( ! interface_exists( WP_Agent_Exclusive_Run_Control_Store::class ) ) {
require_once __DIR__ . '/interface-wp-agent-exclusive-run-control-store.php';
}
if ( ! class_exists( __NAMESPACE__ . '\\WP_Agent_Run_Control_Store_Exception', false ) ) {
require_once __DIR__ . '/class-wp-agent-run-control-store-exception.php';
}
/**
* Persists run-control state in WordPress options.
*/
class WP_Agent_Option_Run_Control_Store implements WP_Agent_Atomic_Workspace_Run_Control_Store, WP_Agent_Exclusive_Run_Control_Store {
private const LOCK_PREFIX = '_agents_api_run_lock_';
private const LOCK_WAIT_SECONDS = 5.0;
private const LOCK_TTL_SECONDS = 15.0;
private ?\wpdb $database;
/** @var array<string,true> */
private array $active_claims = array();
public function __construct( ?\wpdb $database = null ) {
$this->database = $database;
}
/**
* @param string $store_key Store key.
* @return array{runs:array<string,array<string,mixed>>,queues:array<string,array<int,array<string,mixed>>>,events:array<string,array<int,array<string,mixed>>>}
*/
public function get_state( string $store_key ): array {
if ( ! function_exists( 'get_option' ) ) {
return array( 'runs' => array(), 'queues' => array(), 'events' => array() );
}
$db = $this->wordpress_database();
$state = $this->read_wordpress_option( $db, static fn() => get_option( $store_key, array() ) );
if ( ! is_array( $state ) ) {
$state = array();
}
return array(
'runs' => $this->stored_runs( $state['runs'] ?? array() ),
'queues' => $this->stored_queues( $state['queues'] ?? array() ),
'events' => $this->stored_queues( $state['events'] ?? array() ),
);
}
/**
* @param string $store_key Store key.
* @param array{runs:array<string,array<string,mixed>>,queues:array<string,array<int,array<string,mixed>>>,events:array<string,array<int,array<string,mixed>>>} $state State envelope.
*/
public function save_state( string $store_key, array $state ): void {
if ( ! function_exists( 'update_option' ) ) {
return;
}
if ( ! function_exists( 'get_option' ) ) {
throw new \RuntimeException( 'The run-control store requires a readable WordPress options API.' );
}
$db = $this->wordpress_database();
$updated = $this->write_wordpress_option( $db, static fn() => update_option( $store_key, $state, false ) );
if ( ! $updated && null !== $db ) {
// False also represents unchanged values and intentional filter vetoes.
// The direct read verifies DB availability without consulting API caches.
$this->read_option_state( $db, $db->options, $store_key );
}
}
public function mutate_state( string $store_key, callable $mutation ): mixed {
$db = $this->database();
$table = $db->options;
$lock_key = $this->lock_option_key( 'site:' . $table . ':' . $store_key );
$lock_value = $this->acquire_lock( $db, $table, $lock_key );
$primary_error = null;
try {
$state = $this->read_option_state( $db, $table, $store_key );
$mutated = $this->mutation_result( $mutation( $state ) );
$lock_value = $this->commit_under_lock(
$db,
$table,
$lock_key,
$lock_value,
fn() => $this->write_option_state( $db, $table, $store_key, $mutated['state'] )
);
$this->refresh_site_cache( $store_key, $mutated['state'] );
return $mutated['result'];
} catch ( \Throwable $error ) {
$primary_error = $error;
throw $error;
} finally {
try {
$this->release_lock( $db, $table, $lock_key, $lock_value );
} catch ( \Throwable $release_error ) {
if ( null === $primary_error ) {
throw $release_error;
}
}
}
}
/**
* Read explicit workspace state from the network-wide option table.
*
* Omitted workspaces continue through get_state() and remain site-local.
*
* @return array{runs:array<string,array<string,mixed>>,queues:array<string,array<int,array<string,mixed>>>,events:array<string,array<int,array<string,mixed>>>}
*/
public function get_workspace_state( string $store_key, WP_Agent_Workspace_Scope $workspace ): array {
if ( ! function_exists( 'get_site_option' ) ) {
throw new \RuntimeException( 'The run-control store cannot share explicit workspace state.' );
}
$db = $this->wordpress_database();
$state = $this->read_wordpress_option( $db, fn() => get_site_option( $this->workspace_option_key( $store_key, $workspace ), array() ) );
if ( ! is_array( $state ) ) {
$state = array();
}
return array(
'runs' => $this->stored_runs( $state['runs'] ?? array() ),
'queues' => $this->stored_queues( $state['queues'] ?? array() ),
'events' => $this->stored_queues( $state['events'] ?? array() ),
);
}
/**
* Save explicit workspace state in the network-wide option table.
*
* @param array{runs:array<string,array<string,mixed>>,queues:array<string,array<int,array<string,mixed>>>,events:array<string,array<int,array<string,mixed>>>} $state State envelope.
*/
public function save_workspace_state( string $store_key, WP_Agent_Workspace_Scope $workspace, array $state ): void {
if ( ! function_exists( 'update_site_option' ) || ! function_exists( 'get_site_option' ) ) {
throw new \RuntimeException( 'The run-control store cannot share explicit workspace state.' );
}
$option_key = $this->workspace_option_key( $store_key, $workspace );
$db = $this->wordpress_database();
$updated = $this->write_wordpress_option( $db, static fn() => update_site_option( $option_key, $state ) );
if ( ! $updated && null !== $db ) {
$this->read_workspace_state( $db, $option_key );
}
}
public function execute_claimed( string $claim_key, callable $callback ): bool {
$db = $this->database();
$lock_name = 'agents-api:' . substr( hash( 'sha256', $claim_key ), 0, 53 );
if ( isset( $this->active_claims[ $lock_name ] ) ) {
return false;
}
$acquired = $this->get_var( $db, $db->prepare( 'SELECT GET_LOCK(%s, 0)', $lock_name ) );
if ( 0 === $acquired || '0' === $acquired ) {
return false;
}
if ( 1 !== $acquired && '1' !== $acquired ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Run-control claim acquisition failed.' );
}
$this->active_claims[ $lock_name ] = true;
$primary_error = null;
try {
$callback();
return true;
} catch ( \Throwable $error ) {
$primary_error = $error;
throw $error;
} finally {
unset( $this->active_claims[ $lock_name ] );
try {
$released = $this->get_var( $db, $db->prepare( 'SELECT RELEASE_LOCK(%s)', $lock_name ) );
if ( 1 !== $released && '1' !== $released ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Run-control claim release failed.' );
}
} catch ( \Throwable $release_error ) {
if ( null === $primary_error ) {
throw $release_error;
}
}
}
}
public function mutate_workspace_state( string $store_key, WP_Agent_Workspace_Scope $workspace, callable $mutation ): mixed {
$db = $this->database();
$option_key = $this->workspace_option_key( $store_key, $workspace );
if ( function_exists( 'is_multisite' ) && ! is_multisite() ) {
return $this->mutate_state( $option_key, $mutation );
}
$lock_table = $this->main_options_table( $db );
$lock_key = $this->lock_option_key( 'workspace:' . $db->sitemeta . ':' . $this->network_id( $db ) . ':' . $option_key );
$lock_value = $this->acquire_lock( $db, $lock_table, $lock_key );
$primary_error = null;
try {
$state = $this->read_workspace_state( $db, $option_key );
$mutated = $this->mutation_result( $mutation( $state ) );
$lock_value = $this->commit_under_lock(
$db,
$lock_table,
$lock_key,
$lock_value,
fn() => $this->write_workspace_state( $db, $option_key, $mutated['state'] )
);
$this->refresh_workspace_cache( $this->network_id( $db ), $option_key, $mutated['state'] );
return $mutated['result'];
} catch ( \Throwable $error ) {
$primary_error = $error;
throw $error;
} finally {
try {
$this->release_lock( $db, $lock_table, $lock_key, $lock_value );
} catch ( \Throwable $release_error ) {
if ( null === $primary_error ) {
throw $release_error;
}
}
}
}
private function workspace_option_key( string $store_key, WP_Agent_Workspace_Scope $workspace ): string {
return $store_key . '_workspace_' . hash( 'sha256', $workspace->key() );
}
private function database(): \wpdb {
if ( $this->database instanceof \wpdb ) {
return $this->database;
}
global $wpdb;
if ( ! $wpdb instanceof \wpdb ) {
throw new \RuntimeException( 'Atomic run-control mutation requires a WordPress database connection.' );
}
return $wpdb;
}
private function wordpress_database(): ?\wpdb {
if ( $this->database instanceof \wpdb ) {
return $this->database;
}
global $wpdb;
return $wpdb instanceof \wpdb ? $wpdb : null;
}
private function main_options_table( \wpdb $db ): string {
$network_id = $this->network_id( $db );
$main_site_id = function_exists( 'get_main_site_id' ) ? (int) get_main_site_id( $network_id ) : 1;
return $db->get_blog_prefix( max( 1, $main_site_id ) ) . 'options';
}
private function network_id( \wpdb $db ): int {
return max( 1, (int) $db->siteid );
}
private function lock_option_key( string $scope ): string {
return self::LOCK_PREFIX . hash( 'sha256', $scope );
}
private function acquire_lock( \wpdb $db, string $table, string $lock_key ): string {
$token = $this->lock_token();
$deadline = microtime( true ) + self::LOCK_WAIT_SECONDS;
do {
$lock_value = $this->lock_value( $token );
$created = $this->lock_query( $db, $db->prepare( "INSERT IGNORE INTO %i (option_name, option_value, autoload) VALUES (%s, %s, 'no')", $table, $lock_key, $lock_value ) );
if ( 1 === $created ) {
return $lock_value;
}
if ( false === $created ) {
if ( ! $this->is_transient_lock_contention( $db ) ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Atomic run-control lock creation failed.' );
}
usleep( 50000 );
continue;
}
$current = $this->get_var( $db, $db->prepare( 'SELECT option_value FROM %i WHERE option_name = %s LIMIT 1', $table, $lock_key ) );
if ( is_string( $current ) && $this->lock_expired( $current ) ) {
$replaced = $this->lock_query( $db, $db->prepare( "UPDATE %i SET option_value = %s, autoload = 'no' WHERE option_name = %s AND option_value = %s", $table, $lock_value, $lock_key, $current ) );
if ( 1 === $replaced ) {
return $lock_value;
}
if ( false === $replaced && ! $this->is_transient_lock_contention( $db ) ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Atomic run-control lock takeover failed.' );
}
}
usleep( 50000 );
} while ( microtime( true ) < $deadline );
throw new WP_Agent_Run_Control_Store_Exception( 'Atomic run-control lock acquisition timed out.' );
}
/**
* Two connections racing an `INSERT IGNORE` (or a conditional takeover
* `UPDATE`) against the same unique lock row can make InnoDB report a
* deadlock or a lock-wait timeout instead of the clean "0 rows
* affected" outcome this loop already retries. Both are transient
* admission-race artifacts of the exact contention this method exists
* to serialize, not a genuine query or storage failure, so they get
* the same retry treatment as a lost duplicate-key race.
*/
private function is_transient_lock_contention( \wpdb $db ): bool {
return str_contains( $db->last_error, 'Deadlock found' ) || str_contains( $db->last_error, 'Lock wait timeout' );
}
private function release_lock( \wpdb $db, string $table, string $lock_key, string $lock_value ): void {
$released = $this->query( $db, $db->prepare( 'DELETE FROM %i WHERE option_name = %s AND option_value = %s', $table, $lock_key, $lock_value ) );
if ( false === $released ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Atomic run-control lock release failed.' );
}
}
private function commit_under_lock( \wpdb $db, string $table, string $lock_key, string $lock_value, callable $write ): string {
$decoded = json_decode( $lock_value, true );
if ( ! is_array( $decoded ) || ! is_string( $decoded['token'] ?? null ) ) {
throw new \RuntimeException( 'Atomic run-control lock token is invalid.' );
}
if ( false === $this->query( $db, 'START TRANSACTION' ) ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Atomic run-control transaction could not start.' );
}
try {
$current = $this->get_var( $db, $db->prepare( 'SELECT option_value FROM %i WHERE option_name = %s FOR UPDATE', $table, $lock_key ) );
if ( ! is_string( $current ) || ! hash_equals( $lock_value, $current ) ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Atomic run-control lock ownership was lost before state write.' );
}
$refreshed = $this->lock_value( $decoded['token'] );
$updated = $this->query( $db, $db->prepare( "UPDATE %i SET option_value = %s, autoload = 'no' WHERE option_name = %s AND option_value = %s", $table, $refreshed, $lock_key, $lock_value ) );
if ( 1 !== $updated ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Atomic run-control lock ownership was lost before state write.' );
}
$write();
if ( false === $this->query( $db, 'COMMIT' ) ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Atomic run-control transaction could not commit.' );
}
return $refreshed;
} catch ( \Throwable $error ) {
$this->query( $db, 'ROLLBACK' );
throw $error;
}
}
private function lock_token(): string {
try {
return bin2hex( random_bytes( 16 ) );
} catch ( \Throwable $error ) {
unset( $error );
return hash( 'sha256', uniqid( '', true ) );
}
}
private function lock_value( string $token ): string {
$value = json_encode(
array(
'token' => $token,
'expires_at' => microtime( true ) + self::LOCK_TTL_SECONDS,
)
);
if ( ! is_string( $value ) ) {
throw new \RuntimeException( 'Atomic run-control lock could not be encoded.' );
}
return $value;
}
private function lock_expired( string $lock_value ): bool {
$decoded = json_decode( $lock_value, true );
return ! is_array( $decoded ) || ! is_numeric( $decoded['expires_at'] ?? null ) || (float) $decoded['expires_at'] <= microtime( true );
}
/** @return array{runs:array<string,array<string,mixed>>,queues:array<string,array<int,array<string,mixed>>>,events:array<string,array<int,array<string,mixed>>>} */
private function read_option_state( \wpdb $db, string $table, string $store_key ): array {
$value = $this->get_var( $db, $db->prepare( 'SELECT option_value FROM %i WHERE option_name = %s LIMIT 1', $table, $store_key ) );
return $this->decode_state( $value );
}
/** @param array{runs:array<string,array<string,mixed>>,queues:array<string,array<int,array<string,mixed>>>,events:array<string,array<int,array<string,mixed>>>} $state */
private function write_option_state( \wpdb $db, string $table, string $store_key, array $state ): void {
$written = $this->query( $db, $db->prepare( "INSERT INTO %i (option_name, option_value, autoload) VALUES (%s, %s, 'no') ON DUPLICATE KEY UPDATE option_value = VALUES(option_value), autoload = 'no'", $table, $store_key, $this->serialize_value( $state ) ) );
if ( false === $written ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Atomic run-control state write failed.' );
}
}
/** @return array{runs:array<string,array<string,mixed>>,queues:array<string,array<int,array<string,mixed>>>,events:array<string,array<int,array<string,mixed>>>} */
private function read_workspace_state( \wpdb $db, string $option_key ): array {
$value = $this->get_var( $db, $db->prepare( 'SELECT meta_value FROM %i WHERE site_id = %d AND meta_key = %s ORDER BY meta_id ASC LIMIT 1', $db->sitemeta, $this->network_id( $db ), $option_key ) );
return $this->decode_state( $value );
}
/** @param array{runs:array<string,array<string,mixed>>,queues:array<string,array<int,array<string,mixed>>>,events:array<string,array<int,array<string,mixed>>>} $state */
private function write_workspace_state( \wpdb $db, string $option_key, array $state ): void {
$value = $this->serialize_value( $state );
$updated = $this->query( $db, $db->prepare( 'UPDATE %i SET meta_value = %s WHERE site_id = %d AND meta_key = %s', $db->sitemeta, $value, $this->network_id( $db ), $option_key ) );
if ( false === $updated ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Atomic workspace run-control state write failed.' );
}
if ( 0 === $updated ) {
$existing = $this->get_var( $db, $db->prepare( 'SELECT meta_id FROM %i WHERE site_id = %d AND meta_key = %s LIMIT 1', $db->sitemeta, $this->network_id( $db ), $option_key ) );
if ( null !== $existing ) {
return;
}
$inserted = $this->query( $db, $db->prepare( 'INSERT INTO %i (site_id, meta_key, meta_value) VALUES (%d, %s, %s)', $db->sitemeta, $this->network_id( $db ), $option_key, $value ) );
if ( false === $inserted ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Atomic workspace run-control state creation failed.' );
}
if ( 1 !== $inserted ) {
throw new \RuntimeException( 'Atomic workspace run-control state creation failed.' );
}
}
}
private function serialize_value( mixed $value ): string {
$serialized = function_exists( 'maybe_serialize' ) ? maybe_serialize( $value ) : serialize( $value );
return is_string( $serialized ) ? $serialized : serialize( $serialized );
}
private function unserialize_value( mixed $value ): mixed {
if ( ! is_string( $value ) ) {
return array();
}
return function_exists( 'maybe_unserialize' ) ? maybe_unserialize( $value ) : @unserialize( $value );
}
/** @return array{runs:array<string,array<string,mixed>>,queues:array<string,array<int,array<string,mixed>>>,events:array<string,array<int,array<string,mixed>>>} */
private function decode_state( mixed $value ): array {
if ( null === $value ) {
return $this->normalize_state( array() );
}
$state = $this->unserialize_value( $value );
if ( ! is_array( $state ) || ! $this->valid_state_shape( $state ) ) {
throw new \RuntimeException( 'Atomic run-control state is corrupt.' );
}
return $this->normalize_state( $state );
}
/** @param array<mixed> $state */
private function valid_state_shape( array $state ): bool {
$runs = $state['runs'] ?? array();
$queues = $state['queues'] ?? array();
$events = $state['events'] ?? array();
if ( ! is_array( $runs ) || ! is_array( $queues ) || ! is_array( $events ) ) {
return false;
}
foreach ( $runs as $run_id => $run ) {
if ( ! is_string( $run_id ) || ! is_array( $run ) ) {
return false;
}
}
foreach ( array( $queues, $events ) as $collection ) {
foreach ( $collection as $scope => $items ) {
if ( ! is_string( $scope ) || ! is_array( $items ) ) {
return false;
}
foreach ( $items as $item ) {
if ( ! is_array( $item ) ) {
return false;
}
}
}
}
return true;
}
/** @return array{runs:array<string,array<string,mixed>>,queues:array<string,array<int,array<string,mixed>>>,events:array<string,array<int,array<string,mixed>>>} */
private function normalize_state( mixed $state ): array {
$state = is_array( $state ) ? $state : array();
return array(
'runs' => $this->stored_runs( $state['runs'] ?? array() ),
'queues' => $this->stored_queues( $state['queues'] ?? array() ),
'events' => $this->stored_queues( $state['events'] ?? array() ),
);
}
/** @return array{state:array{runs:array<string,array<string,mixed>>,queues:array<string,array<int,array<string,mixed>>>,events:array<string,array<int,array<string,mixed>>>},result:mixed} */
private function mutation_result( mixed $mutation ): array {
if ( ! is_array( $mutation ) || ! is_array( $mutation['state'] ?? null ) || ! array_key_exists( 'result', $mutation ) ) {
throw new \RuntimeException( 'Atomic run-control mutations must return state and result.' );
}
return array(
'state' => $this->normalize_state( $mutation['state'] ),
'result' => $mutation['result'],
);
}
/** @param array{runs:array<string,array<string,mixed>>,queues:array<string,array<int,array<string,mixed>>>,events:array<string,array<int,array<string,mixed>>>} $state */
private function refresh_site_cache( string $store_key, array $state ): void {
if ( function_exists( 'wp_cache_delete' ) ) {
wp_cache_delete( $store_key, 'options' );
wp_cache_delete( 'notoptions', 'options' );
wp_cache_delete( 'alloptions', 'options' );
}
if ( function_exists( 'wp_cache_set' ) ) {
wp_cache_set( $store_key, $state, 'options' );
}
}
/** @param array{runs:array<string,array<string,mixed>>,queues:array<string,array<int,array<string,mixed>>>,events:array<string,array<int,array<string,mixed>>>} $state */
private function refresh_workspace_cache( int $network_id, string $option_key, array $state ): void {
if ( function_exists( 'wp_cache_delete' ) ) {
wp_cache_delete( $network_id . ':' . $option_key, 'site-options' );
wp_cache_delete( $network_id . ':notoptions', 'site-options' );
}
if ( function_exists( 'wp_cache_set' ) ) {
wp_cache_set( $network_id . ':' . $option_key, $state, 'site-options' );
}
}
/** @return int|bool */
private function query( \wpdb $db, ?string $query ) {
if ( ! is_string( $query ) ) {
throw new \RuntimeException( 'Atomic run-control query preparation failed.' );
}
return $db->query( $query );
}
private function get_var( \wpdb $db, ?string $query ): mixed {
if ( ! is_string( $query ) ) {
throw new \RuntimeException( 'Atomic run-control query preparation failed.' );
}
$db->last_error = '';
$value = $db->get_var( $query );
if ( $this->database_has_error( $db ) ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Atomic run-control state read failed.' );
}
return $value;
}
private function read_wordpress_option( ?\wpdb $db, callable $read ): mixed {
global $wpdb;
$previous_database = $wpdb ?? null;
if ( null !== $db ) {
$db->last_error = '';
$wpdb = $db;
}
try {
$value = $read();
} finally {
if ( null !== $db ) {
$wpdb = $previous_database;
}
}
if ( $this->database_has_error( $db ) ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Run-control state read failed.' );
}
return $value;
}
private function write_wordpress_option( ?\wpdb $db, callable $write ): bool {
global $wpdb;
$previous_database = $wpdb ?? null;
if ( null !== $db ) {
$db->last_error = '';
$wpdb = $db;
}
try {
$written = $write();
} finally {
if ( null !== $db ) {
$wpdb = $previous_database;
}
}
if ( $this->database_has_error( $db ) ) {
throw new WP_Agent_Run_Control_Store_Exception( 'Run-control state write failed.' );
}
return (bool) $written;
}
private function database_has_error( ?\wpdb $db ): bool {
return null !== $db && '' !== $db->last_error;
}
/** @return int|bool */
private function lock_query( \wpdb $db, ?string $query ) {
$previous = $db->suppress_errors( true );
try {
return $this->query( $db, $query );
} finally {
$db->suppress_errors( $previous );
}
}
/**
* @param mixed $runs Raw stored runs.
* @return array<string,array<string,mixed>>
*/
private function stored_runs( mixed $runs ): array {
if ( ! is_array( $runs ) ) {
return array();
}
$stored = array();
foreach ( $runs as $run_id => $run ) {
if ( is_string( $run_id ) && is_array( $run ) ) {
$stored[ $run_id ] = $this->assoc_array( $run );
}
}
return $stored;
}
/**
* @param mixed $queues Raw stored queues.
* @return array<string,array<int,array<string,mixed>>>
*/
private function stored_queues( mixed $queues ): array {
if ( ! is_array( $queues ) ) {
return array();
}
$stored = array();
foreach ( $queues as $scope => $items ) {
if ( ! is_string( $scope ) || ! is_array( $items ) ) {
continue;
}
$stored[ $scope ] = array();
foreach ( $items as $item ) {
if ( is_array( $item ) ) {
$stored[ $scope ][] = $this->assoc_array( $item );
}
}
}
return $stored;
}
/**
* @param array<mixed> $value Raw array.
* @return array<string,mixed>
*/
private function assoc_array( array $value ): array {
$result = array();
foreach ( $value as $key => $item ) {
if ( is_string( $key ) ) {
$result[ $key ] = $item;
}
}
return $result;
}
}