PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 4.2.5
Jetpack – WP Security, Backup, Speed, & Growth v4.2.5
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / sync / class.jetpack-sync-queue.php

class.jetpack-sync-queue.php in Jetpack – WP Security, Backup, Speed, & Growth 4.2.5, at sync/class.jetpack-sync-queue.php

420 lines 11.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * A buffer of items from the queue that can be checked out
5 */
6 class Jetpack_Sync_Queue_Buffer {
7 public $id;
8 public $items_with_ids;
9
10 public function __construct( $id, $items_with_ids ) {
11 $this->id = $id;
12 $this->items_with_ids = $items_with_ids;
13 }
14
15 public function get_items() {
16 return array_combine( $this->get_item_ids(), $this->get_item_values() );
17 }
18
19 public function get_item_values() {
20 return Jetpack_Sync_Utils::get_item_values( $this->items_with_ids );
21 }
22
23 public function get_item_ids() {
24 return Jetpack_Sync_Utils::get_item_ids( $this->items_with_ids );
25 }
26 }
27
28 /**
29 * A persistent queue that can be flushed in increments of N items,
30 * and which blocks reads until checked-out buffers are checked in or
31 * closed. This uses raw SQL for two reasons: speed, and not triggering
32 * tons of added_option callbacks.
33 */
34 class Jetpack_Sync_Queue {
35 public $id;
36 private $row_iterator;
37
38 function __construct( $id ) {
39 $this->id = str_replace( '-', '_', $id ); // necessary to ensure we don't have ID collisions in the SQL
40 $this->row_iterator = 0;
41 }
42
43 function add( $item ) {
44 global $wpdb;
45 $added = false;
46 // this basically tries to add the option until enough time has elapsed that
47 // it has a unique (microtime-based) option key
48 while ( ! $added ) {
49 $rows_added = $wpdb->query( $wpdb->prepare(
50 "INSERT INTO $wpdb->options (option_name, option_value,autoload) VALUES (%s, %s,%s)",
51 $this->get_next_data_row_option_name(),
52 serialize( $item ),
53 'no'
54 ) );
55 $added = ( 0 !== $rows_added );
56 }
57
58 do_action( 'jpsq_item_added' );
59 }
60
61 // Attempts to insert all the items in a single SQL query. May be subject to query size limits!
62 function add_all( $items ) {
63 global $wpdb;
64 $base_option_name = $this->get_next_data_row_option_name();
65
66 $query = "INSERT INTO $wpdb->options (option_name, option_value,autoload) VALUES ";
67
68 $rows = array();
69
70 for ( $i = 0; $i < count( $items ); $i += 1 ) {
71 $option_name = esc_sql( $base_option_name . '-' . $i );
72 $option_value = esc_sql( serialize( $items[ $i ] ) );
73 $rows[] = "('$option_name', '$option_value', 'no')";
74 }
75
76 $rows_added = $wpdb->query( $query . join( ',', $rows ) );
77
78 if ( count( $items ) === $rows_added ) {
79 return new WP_Error( 'row_count_mismatch', "The number of rows inserted didn't match the size of the input array" );
80 }
81
82 do_action( 'jpsq_items_added', $rows_added );
83 }
84
85 // Peek at the front-most item on the queue without checking it out
86 function peek( $count = 1 ) {
87 $items = $this->fetch_items( $count );
88 if ( $items ) {
89 return Jetpack_Sync_Utils::get_item_values( $items );
90 }
91
92 return array();
93 }
94
95 // lag is the difference in time between the age of the oldest item
96 // (aka first or frontmost item) and the current time
97 function lag() {
98 return self::get_lag( $this->id );
99 }
100
101 static function get_lag( $id ) {
102 global $wpdb;
103
104 $first_item_name = $wpdb->get_var( $wpdb->prepare(
105 "SELECT option_name FROM $wpdb->options WHERE option_name LIKE %s ORDER BY option_name ASC LIMIT 1",
106 "jpsq_{$id}-%"
107 ) );
108
109 if ( ! $first_item_name ) {
110 return 0;
111 }
112
113 // break apart the item name to get the timestamp
114 $matches = null;
115 if ( preg_match( '/^jpsq_' . $id . '-(\d+\.\d+)-/', $first_item_name, $matches ) ) {
116 return microtime( true ) - floatval( $matches[1] );
117 } else {
118 return 0;
119 }
120 }
121
122 function reset() {
123 global $wpdb;
124 $this->delete_checkout_id();
125 $wpdb->query( $wpdb->prepare(
126 "DELETE FROM $wpdb->options WHERE option_name LIKE %s", "jpsq_{$this->id}-%"
127 ) );
128 }
129
130 function size() {
131 global $wpdb;
132
133 return (int) $wpdb->get_var( $wpdb->prepare(
134 "SELECT count(*) FROM $wpdb->options WHERE option_name LIKE %s", "jpsq_{$this->id}-%"
135 ) );
136 }
137
138 // we use this peculiar implementation because it's much faster than count(*)
139 function has_any_items() {
140 global $wpdb;
141 $value = $wpdb->get_var( $wpdb->prepare(
142 "SELECT exists( SELECT option_name FROM $wpdb->options WHERE option_name LIKE %s )", "jpsq_{$this->id}-%"
143 ) );
144
145 return ( $value === '1' );
146 }
147
148 function checkout( $buffer_size ) {
149 if ( $this->get_checkout_id() ) {
150 return new WP_Error( 'unclosed_buffer', 'There is an unclosed buffer' );
151 }
152
153 $buffer_id = uniqid();
154
155 $result = $this->set_checkout_id( $buffer_id );
156
157 if ( ! $result || is_wp_error( $result ) ) {
158 return $result;
159 }
160
161 $items = $this->fetch_items( $buffer_size );
162
163 if ( count( $items ) === 0 ) {
164 return false;
165 }
166
167 $buffer = new Jetpack_Sync_Queue_Buffer( $buffer_id, array_slice( $items, 0, $buffer_size ) );
168
169 return $buffer;
170 }
171
172 // this checks out rows until it either empties the queue or hits a certain memory limit
173 // it loads the sizes from the DB first so that it doesn't accidentally
174 // load more data into memory than it needs to.
175 // The only way it will load more items than $max_size is if a single queue item
176 // exceeds the memory limit, but in that case it will send that item by itself.
177 function checkout_with_memory_limit( $max_memory, $max_buffer_size = 500 ) {
178 if ( $this->get_checkout_id() ) {
179 return new WP_Error( 'unclosed_buffer', 'There is an unclosed buffer' );
180 }
181
182 $buffer_id = uniqid();
183
184 $result = $this->set_checkout_id( $buffer_id );
185
186 if ( ! $result || is_wp_error( $result ) ) {
187 return $result;
188 }
189
190 // get the map of buffer_id -> memory_size
191 global $wpdb;
192
193 $items_with_size = $wpdb->get_results(
194 $wpdb->prepare(
195 "SELECT option_name AS id, LENGTH(option_value) AS value_size FROM $wpdb->options WHERE option_name LIKE %s ORDER BY option_name ASC LIMIT %d",
196 "jpsq_{$this->id}-%",
197 $max_buffer_size
198 ),
199 OBJECT
200 );
201
202 $total_memory = 0;
203 $item_ids = array();
204
205 foreach ( $items_with_size as $item_with_size ) {
206 $total_memory += $item_with_size->value_size;
207
208 // if this is the first item and it exceeds memory, allow loop to continue
209 // we will exit on the next iteration instead
210 if ( $total_memory > $max_memory && count( $item_ids ) > 0 ) {
211 break;
212 }
213 $item_ids[] = $item_with_size->id;
214 }
215
216 $items = $this->fetch_items_by_id( $item_ids );
217
218 if ( count( $items ) === 0 ) {
219 $this->delete_checkout_id();
220
221 return false;
222 }
223
224 $buffer = new Jetpack_Sync_Queue_Buffer( $buffer_id, $items );
225
226 return $buffer;
227 }
228
229 function checkin( $buffer ) {
230 $is_valid = $this->validate_checkout( $buffer );
231
232 if ( is_wp_error( $is_valid ) ) {
233 return $is_valid;
234 }
235
236 $this->delete_checkout_id();
237
238 return true;
239 }
240
241 function close( $buffer, $ids_to_remove = null ) {
242 $is_valid = $this->validate_checkout( $buffer );
243
244 if ( is_wp_error( $is_valid ) ) {
245 return $is_valid;
246 }
247
248 $this->delete_checkout_id();
249
250 // by default clear all items in the buffer
251 if ( is_null( $ids_to_remove ) ) {
252 $ids_to_remove = $buffer->get_item_ids();
253 }
254
255 global $wpdb;
256
257 if ( count( $ids_to_remove ) > 0 ) {
258 $sql = "DELETE FROM $wpdb->options WHERE option_name IN (" . implode( ', ', array_fill( 0, count( $ids_to_remove ), '%s' ) ) . ')';
259 $query = call_user_func_array( array( $wpdb, 'prepare' ), array_merge( array( $sql ), $ids_to_remove ) );
260 $wpdb->query( $query );
261 }
262
263 return true;
264 }
265
266 function flush_all() {
267 $items = Jetpack_Sync_Utils::get_item_values( $this->fetch_items() );
268 $this->reset();
269
270 return $items;
271 }
272
273 function get_all() {
274 return $this->fetch_items();
275 }
276
277 // use with caution, this could allow multiple processes to delete
278 // and send from the queue at the same time
279 function force_checkin() {
280 $this->delete_checkout_id();
281 }
282
283 // used to lock checkouts from the queue.
284 // tries to wait up to $timeout seconds for the queue to be empty
285 function lock( $timeout = 30 ) {
286 $tries = 0;
287
288 while ( $this->has_any_items() && $tries < $timeout ) {
289 sleep( 1 );
290 $tries += 1;
291 }
292
293 if ( $tries === 30 ) {
294 return new WP_Error( 'lock_timeout', 'Timeout waiting for sync queue to empty' );
295 }
296
297 if ( $this->get_checkout_id() ) {
298 return new WP_Error( 'unclosed_buffer', 'There is an unclosed buffer' );
299 }
300
301 // hopefully this means we can acquire a checkout?
302 $result = $this->set_checkout_id( 'lock' );
303
304 if ( ! $result || is_wp_error( $result ) ) {
305 return $result;
306 }
307
308 return true;
309 }
310
311 function unlock() {
312 $this->delete_checkout_id();
313 }
314
315 private function get_checkout_id() {
316 return get_transient( $this->get_checkout_transient_name() );
317 }
318
319 private function set_checkout_id( $checkout_id ) {
320 return set_transient( $this->get_checkout_transient_name(), $checkout_id, 5 * 60 ); // 5 minute timeout
321 }
322
323 private function delete_checkout_id() {
324 delete_transient( $this->get_checkout_transient_name() );
325 }
326
327 private function get_checkout_transient_name() {
328 return "jpsq_{$this->id}_checkout";
329 }
330
331 private function get_next_data_row_option_name() {
332 // this option is specifically chosen to, as much as possible, preserve time order
333 // and minimise the possibility of collisions between multiple processes working
334 // at the same time
335 // TODO: confirm we only need to support PHP 5.05+ (otherwise we'll need to emulate microtime as float, and avoid PHP_INT_MAX)
336 // @see: http://php.net/manual/en/function.microtime.php
337 $timestamp = sprintf( '%.6f', microtime( true ) );
338
339 // row iterator is used to avoid collisions where we're writing data waaay fast in a single process
340 if ( $this->row_iterator === PHP_INT_MAX ) {
341 $this->row_iterator = 0;
342 } else {
343 $this->row_iterator += 1;
344 }
345
346 return 'jpsq_' . $this->id . '-' . $timestamp . '-' . getmypid() . '-' . $this->row_iterator;
347 }
348
349 private function fetch_items( $limit = null ) {
350 global $wpdb;
351
352 if ( $limit ) {
353 $query_sql = $wpdb->prepare( "SELECT option_name AS id, option_value AS value FROM $wpdb->options WHERE option_name LIKE %s ORDER BY option_name ASC LIMIT %d", "jpsq_{$this->id}-%", $limit );
354 } else {
355 $query_sql = $wpdb->prepare( "SELECT option_name AS id, option_value AS value FROM $wpdb->options WHERE option_name LIKE %s ORDER BY option_name ASC", "jpsq_{$this->id}-%" );
356 }
357
358 $items = $wpdb->get_results( $query_sql, OBJECT );
359 foreach ( $items as $item ) {
360 $item->value = maybe_unserialize( $item->value );
361 }
362
363 return $items;
364 }
365
366 private function fetch_items_by_id( $item_ids ) {
367 global $wpdb;
368
369 if ( count( $item_ids ) > 0 ) {
370 $sql = "SELECT option_name AS id, option_value AS value FROM $wpdb->options WHERE option_name IN (" . implode( ', ', array_fill( 0, count( $item_ids ), '%s' ) ) . ') ORDER BY option_name ASC';
371 $query = call_user_func_array( array( $wpdb, 'prepare' ), array_merge( array( $sql ), $item_ids ) );
372 $items = $wpdb->get_results( $query, OBJECT );
373 foreach ( $items as $item ) {
374 $item->value = maybe_unserialize( $item->value );
375 }
376
377 return $items;
378 } else {
379 return array();
380 }
381 }
382
383 private function validate_checkout( $buffer ) {
384 if ( ! $buffer instanceof Jetpack_Sync_Queue_Buffer ) {
385 return new WP_Error( 'not_a_buffer', 'You must checkin an instance of Jetpack_Sync_Queue_Buffer' );
386 }
387
388 $checkout_id = $this->get_checkout_id();
389
390 if ( ! $checkout_id ) {
391 return new WP_Error( 'buffer_not_checked_out', 'There are no checked out buffers' );
392 }
393
394 if ( $checkout_id != $buffer->id ) {
395 return new WP_Error( 'buffer_mismatch', 'The buffer you checked in was not checked out' );
396 }
397
398 return true;
399 }
400 }
401
402 class Jetpack_Sync_Utils {
403
404 static function get_item_values( $items ) {
405 return array_map( array( __CLASS__, 'get_item_value' ), $items );
406 }
407
408 static function get_item_ids( $items ) {
409 return array_map( array( __CLASS__, 'get_item_id' ), $items );
410 }
411
412 static private function get_item_value( $item ) {
413 return $item->value;
414 }
415
416 static private function get_item_id( $item ) {
417 return $item->id;
418 }
419 }
420