Completed
Push — fix/production-builds ( 301e61...f5e011 )
by
unknown
288:28 queued 279:29
created

Full_Sync::continue_enqueuing()   C

Complexity

Conditions 14
Paths 26

Size

Total Lines 75

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
nc 26
nop 2
dl 0
loc 75
rs 5.5587
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Automattic\Jetpack\Sync\Modules;
4
5
use Automattic\Jetpack\Sync\Listener;
6
use Automattic\Jetpack\Sync\Queue;
7
8
/**
9
 * This class does a full resync of the database by
10
 * enqueuing an outbound action for every single object
11
 * that we care about.
12
 *
13
 * This class, and its related class Jetpack_Sync_Module, contain a few non-obvious optimisations that should be explained:
14
 * - we fire an action called jetpack_full_sync_start so that WPCOM can erase the contents of the cached database
15
 * - for each object type, we page through the object IDs and enqueue them by firing some monitored actions
16
 * - we load the full objects for those IDs in chunks of Jetpack_Sync_Module::ARRAY_CHUNK_SIZE (to reduce the number of MySQL calls)
17
 * - we fire a trigger for the entire array which the Automattic\Jetpack\Sync\Listener then serializes and queues.
18
 */
19
20
class Full_Sync extends \Jetpack_Sync_Module {
21
	const STATUS_OPTION_PREFIX = 'jetpack_sync_full_';
22
	const FULL_SYNC_TIMEOUT    = 3600;
23
24
	public function name() {
25
		return 'full-sync';
26
	}
27
28
	function init_full_sync_listeners( $callable ) {
29
		// synthetic actions for full sync
30
		add_action( 'jetpack_full_sync_start', $callable, 10, 3 );
31
		add_action( 'jetpack_full_sync_end', $callable, 10, 2 );
32
		add_action( 'jetpack_full_sync_cancelled', $callable );
33
	}
34
35
	function init_before_send() {
36
		// this is triggered after actions have been processed on the server
37
		add_action( 'jetpack_sync_processed_actions', array( $this, 'update_sent_progress_action' ) );
38
	}
39
40
	function start( $module_configs = null ) {
41
		$was_already_running = $this->is_started() && ! $this->is_finished();
42
43
		// remove all evidence of previous full sync items and status
44
		$this->reset_data();
45
46
		if ( $was_already_running ) {
47
			/**
48
			 * Fires when a full sync is cancelled.
49
			 *
50
			 * @since 4.2.0
51
			 */
52
			do_action( 'jetpack_full_sync_cancelled' );
53
		}
54
55
		$this->update_status_option( 'started', time() );
56
		$this->update_status_option( 'params', $module_configs );
57
58
		$enqueue_status   = array();
59
		$full_sync_config = array();
60
		$include_empty    = false;
61
		$empty            = array();
62
		// default value is full sync
63
		if ( ! is_array( $module_configs ) ) {
64
			$module_configs = array();
65
			$include_empty  = true;
66
			foreach ( \Jetpack_Sync_Modules::get_modules() as $module ) {
67
				$module_configs[ $module->name() ] = true;
68
			}
69
		}
70
71
		// set default configuration, calculate totals, and save configuration if totals > 0
72
		foreach ( \Jetpack_Sync_Modules::get_modules() as $module ) {
73
			$module_name   = $module->name();
74
			$module_config = isset( $module_configs[ $module_name ] ) ? $module_configs[ $module_name ] : false;
75
76
			if ( ! $module_config ) {
77
				continue;
78
			}
79
80
			if ( 'users' === $module_name && 'initial' === $module_config ) {
81
				$module_config = $module->get_initial_sync_user_config();
82
			}
83
84
			$enqueue_status[ $module_name ] = false;
85
86
			$total_items = $module->estimate_full_sync_actions( $module_config );
87
88
			// if there's information to process, configure this module
89
			if ( ! is_null( $total_items ) && $total_items > 0 ) {
90
				$full_sync_config[ $module_name ] = $module_config;
91
				$enqueue_status[ $module_name ]   = array(
92
					$total_items,   // total
93
					0,              // queued
94
					false,          // current state
95
				);
96
			} elseif ( $include_empty && $total_items === 0 ) {
97
				$empty[ $module_name ] = true;
98
			}
99
		}
100
101
		$this->set_config( $full_sync_config );
102
		$this->set_enqueue_status( $enqueue_status );
103
104
		$range = $this->get_content_range( $full_sync_config );
105
		/**
106
		 * Fires when a full sync begins. This action is serialized
107
		 * and sent to the server so that it knows a full sync is coming.
108
		 *
109
		 * @since 4.2.0
110
		 * @since 7.3.0 Added $range arg.
111
		 * @since 7.4.0 Added $empty arg.
112
		 *
113
		 * @param array $full_sync_config Sync configuration for all sync modules.
114
		 * @param array $range            Range of the sync items, containing min and max IDs for some item types.
115
		 * @param array $empty            The modules with no items to sync during a full sync.
116
		 */
117
		do_action( 'jetpack_full_sync_start', $full_sync_config, $range, $empty );
118
119
		$this->continue_enqueuing( $full_sync_config, $enqueue_status );
120
121
		return true;
122
	}
123
124
	function continue_enqueuing( $configs = null, $enqueue_status = null ) {
125
		if ( ! $this->is_started() || $this->get_status_option( 'queue_finished' ) ) {
126
			return;
127
		}
128
129
		// if full sync queue is full, don't enqueue more items
130
		$max_queue_size_full_sync = \Jetpack_Sync_Settings::get_setting( 'max_queue_size_full_sync' );
131
		$full_sync_queue          = new Queue( 'full_sync' );
132
133
		$available_queue_slots = $max_queue_size_full_sync - $full_sync_queue->size();
134
135
		if ( $available_queue_slots <= 0 ) {
136
			return;
137
		} else {
138
			$remaining_items_to_enqueue = min( \Jetpack_Sync_Settings::get_setting( 'max_enqueue_full_sync' ), $available_queue_slots );
139
		}
140
141
		if ( ! $configs ) {
142
			$configs = $this->get_config();
143
		}
144
145
		if ( ! $enqueue_status ) {
146
			$enqueue_status = $this->get_enqueue_status();
147
		}
148
149
		foreach ( \Jetpack_Sync_Modules::get_modules() as $module ) {
150
			$module_name = $module->name();
151
152
			// skip module if not configured for this sync or module is done
153
			if ( ! isset( $configs[ $module_name ] )
154
				|| // no module config
155
					! $configs[ $module_name ]
156
				|| // no enqueue status
157
					! $enqueue_status[ $module_name ]
158
				|| // finished enqueuing this module
159
					true === $enqueue_status[ $module_name ][2] ) {
160
				continue;
161
			}
162
163
			list( $items_enqueued, $next_enqueue_state ) = $module->enqueue_full_sync_actions( $configs[ $module_name ], $remaining_items_to_enqueue, $enqueue_status[ $module_name ][2] );
164
165
			$enqueue_status[ $module_name ][2] = $next_enqueue_state;
166
167
			// if items were processed, subtract them from the limit
168
			if ( ! is_null( $items_enqueued ) && $items_enqueued > 0 ) {
169
				$enqueue_status[ $module_name ][1] += $items_enqueued;
170
				$remaining_items_to_enqueue        -= $items_enqueued;
171
			}
172
173
			// stop processing if we've reached our limit of items to enqueue
174
			if ( 0 >= $remaining_items_to_enqueue ) {
175
				$this->set_enqueue_status( $enqueue_status );
176
				return;
177
			}
178
		}
179
180
		$this->set_enqueue_status( $enqueue_status );
181
182
		// setting autoload to true means that it's faster to check whether we should continue enqueuing
183
		$this->update_status_option( 'queue_finished', time(), true );
184
185
		$range = $this->get_content_range( $configs );
186
187
		/**
188
		 * Fires when a full sync ends. This action is serialized
189
		 * and sent to the server.
190
		 *
191
		 * @since 4.2.0
192
		 * @since 7.3.0 Added $range arg.
193
		 *
194
		 * @param string $checksum Deprecated since 7.3.0 - @see https://github.com/Automattic/jetpack/pull/11945/
195
		 * @param array  $range    Range of the sync items, containing min and max IDs for some item types.
196
		 */
197
		do_action( 'jetpack_full_sync_end', '', $range );
198
	}
199
200
	function get_range( $type ) {
201
		global $wpdb;
202
		if ( ! in_array( $type, array( 'comments', 'posts' ) ) ) {
203
			return array();
204
		}
205
206
		switch ( $type ) {
207
			case 'posts':
208
				$table     = $wpdb->posts;
209
				$id        = 'ID';
210
				$where_sql = \Jetpack_Sync_Settings::get_blacklisted_post_types_sql();
211
212
				break;
213
			case 'comments':
214
				$table     = $wpdb->comments;
215
				$id        = 'comment_ID';
216
				$where_sql = \Jetpack_Sync_Settings::get_comments_filter_sql();
217
				break;
218
		}
219
		$results = $wpdb->get_results( "SELECT MAX({$id}) as max, MIN({$id}) as min, COUNT({$id}) as count FROM {$table} WHERE {$where_sql}" );
0 ignored issues
show
Bug introduced by
The variable $id does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $table does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $where_sql does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
220
		if ( isset( $results[0] ) ) {
221
			return $results[0];
222
		}
223
224
		return array();
225
	}
226
227
	private function get_content_range( $config ) {
228
		$range = array();
229
		// Only when we are sending the whole range do we want to send also the range
230 View Code Duplication
		if ( isset( $config['posts'] ) && $config['posts'] === true ) {
231
			$range['posts'] = $this->get_range( 'posts' );
232
		}
233
234 View Code Duplication
		if ( isset( $config['comments'] ) && $config['comments'] === true ) {
235
			$range['comments'] = $this->get_range( 'comments' );
236
		}
237
		return $range;
238
	}
239
240
	function update_sent_progress_action( $actions ) {
241
		// quick way to map to first items with an array of arrays
242
		$actions_with_counts = array_count_values( array_filter( array_map( array( $this, 'get_action_name' ), $actions ) ) );
243
244
		// Total item counts for each action.
245
		$actions_with_total_counts = $this->get_actions_totals( $actions );
246
247
		if ( ! $this->is_started() || $this->is_finished() ) {
248
			return;
249
		}
250
251
		if ( isset( $actions_with_counts['jetpack_full_sync_start'] ) ) {
252
			$this->update_status_option( 'send_started', time() );
253
		}
254
255
		foreach ( \Jetpack_Sync_Modules::get_modules() as $module ) {
256
			$module_actions     = $module->get_full_sync_actions();
257
			$status_option_name = "{$module->name()}_sent";
258
			$total_option_name  = "{$status_option_name}_total";
259
			$items_sent         = $this->get_status_option( $status_option_name, 0 );
260
			$items_sent_total   = $this->get_status_option( $total_option_name, 0 );
261
262
			foreach ( $module_actions as $module_action ) {
263
				if ( isset( $actions_with_counts[ $module_action ] ) ) {
264
					$items_sent += $actions_with_counts[ $module_action ];
265
				}
266
267
				if ( ! empty( $actions_with_total_counts[ $module_action ] ) ) {
268
					$items_sent_total += $actions_with_total_counts[ $module_action ];
269
				}
270
			}
271
272
			if ( $items_sent > 0 ) {
273
				$this->update_status_option( $status_option_name, $items_sent );
274
			}
275
276
			if ( 0 !== $items_sent_total ) {
277
				$this->update_status_option( $total_option_name, $items_sent_total );
278
			}
279
		}
280
281
		if ( isset( $actions_with_counts['jetpack_full_sync_end'] ) ) {
282
			$this->update_status_option( 'finished', time() );
283
		}
284
	}
285
286
	public function get_action_name( $queue_item ) {
287
		if ( is_array( $queue_item ) && isset( $queue_item[0] ) ) {
288
			return $queue_item[0];
289
		}
290
		return false;
291
	}
292
293
	/**
294
	 * Retrieve the total number of items we're syncing in a particular queue item (action).
295
	 * `$queue_item[1]` is expected to contain chunks of items, and `$queue_item[1][0]`
296
	 * represents the first (and only) chunk of items to sync in that action.
297
	 *
298
	 * @param array $queue_item Item of the sync queue that corresponds to a particular action.
299
	 * @return int Total number of items in the action.
300
	 */
301
	public function get_action_totals( $queue_item ) {
302
		if ( is_array( $queue_item ) && isset( $queue_item[1][0] ) ) {
303
			if ( is_array( $queue_item[1][0] ) ) {
304
				// Let's count the items we sync in this action.
305
				return count( $queue_item[1][0] );
306
			}
307
			// -1 indicates that this action syncs all items by design.
308
			return -1;
309
		}
310
		return 0;
311
	}
312
313
	/**
314
	 * Retrieve the total number of items for a set of actions, grouped by action name.
315
	 *
316
	 * @param array $actions An array of actions.
317
	 * @return array An array, representing the total number of items, grouped per action.
318
	 */
319
	public function get_actions_totals( $actions ) {
320
		$totals = array();
321
322
		foreach ( $actions as $action ) {
323
			$name          = $this->get_action_name( $action );
324
			$action_totals = $this->get_action_totals( $action );
325
			if ( ! isset( $totals[ $name ] ) ) {
326
				$totals[ $name ] = 0;
327
			}
328
			$totals[ $name ] += $action_totals;
329
		}
330
331
		return $totals;
332
	}
333
334
	public function is_started() {
335
		return ! ! $this->get_status_option( 'started' );
336
	}
337
338
	public function is_finished() {
339
		return ! ! $this->get_status_option( 'finished' );
340
	}
341
342
	public function get_status() {
343
		$status = array(
344
			'started'        => $this->get_status_option( 'started' ),
345
			'queue_finished' => $this->get_status_option( 'queue_finished' ),
346
			'send_started'   => $this->get_status_option( 'send_started' ),
347
			'finished'       => $this->get_status_option( 'finished' ),
348
			'sent'           => array(),
349
			'sent_total'     => array(),
350
			'queue'          => array(),
351
			'config'         => $this->get_status_option( 'params' ),
352
			'total'          => array(),
353
		);
354
355
		$enqueue_status = $this->get_enqueue_status();
356
357
		foreach ( \Jetpack_Sync_Modules::get_modules() as $module ) {
358
			$name = $module->name();
359
360
			if ( ! isset( $enqueue_status[ $name ] ) ) {
361
				continue;
362
			}
363
364
			list( $total, $queued, $state ) = $enqueue_status[ $name ];
0 ignored issues
show
Unused Code introduced by
The assignment to $state is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
365
366
			if ( $total ) {
367
				$status['total'][ $name ] = $total;
368
			}
369
370
			if ( $queued ) {
371
				$status['queue'][ $name ] = $queued;
372
			}
373
374
			if ( $sent = $this->get_status_option( "{$name}_sent" ) ) {
375
				$status['sent'][ $name ] = $sent;
376
			}
377
378
			$sent_total = $this->get_status_option( "{$name}_sent_total" );
379
			if ( $sent_total ) {
380
				$status['sent_total'][ $name ] = $sent_total;
381
			}
382
		}
383
384
		return $status;
385
	}
386
387
	public function clear_status() {
388
		$prefix = self::STATUS_OPTION_PREFIX;
389
		\Jetpack_Options::delete_raw_option( "{$prefix}_started" );
390
		\Jetpack_Options::delete_raw_option( "{$prefix}_params" );
391
		\Jetpack_Options::delete_raw_option( "{$prefix}_queue_finished" );
392
		\Jetpack_Options::delete_raw_option( "{$prefix}_send_started" );
393
		\Jetpack_Options::delete_raw_option( "{$prefix}_finished" );
394
395
		$this->delete_enqueue_status();
396
397
		foreach ( \Jetpack_Sync_Modules::get_modules() as $module ) {
398
			\Jetpack_Options::delete_raw_option( "{$prefix}_{$module->name()}_sent" );
399
			\Jetpack_Options::delete_raw_option( "{$prefix}_{$module->name()}_sent_total" );
400
		}
401
	}
402
403
	public function reset_data() {
404
		$this->clear_status();
405
		$this->delete_config();
406
407
		$listener = Listener::get_instance();
408
		$listener->get_full_sync_queue()->reset();
409
	}
410
411
	private function get_status_option( $name, $default = null ) {
412
		$value = \Jetpack_Options::get_raw_option( self::STATUS_OPTION_PREFIX . "_$name", $default );
413
414
		return is_numeric( $value ) ? intval( $value ) : $value;
415
	}
416
417
	private function update_status_option( $name, $value, $autoload = false ) {
418
		\Jetpack_Options::update_raw_option( self::STATUS_OPTION_PREFIX . "_$name", $value, $autoload );
419
	}
420
421
	private function set_enqueue_status( $new_status ) {
422
		\Jetpack_Options::update_raw_option( 'jetpack_sync_full_enqueue_status', $new_status );
423
	}
424
425
	private function delete_enqueue_status() {
426
		return \Jetpack_Options::delete_raw_option( 'jetpack_sync_full_enqueue_status' );
427
	}
428
429
	private function get_enqueue_status() {
430
		return \Jetpack_Options::get_raw_option( 'jetpack_sync_full_enqueue_status' );
431
	}
432
433
	private function set_config( $config ) {
434
		\Jetpack_Options::update_raw_option( 'jetpack_sync_full_config', $config );
435
	}
436
437
	private function delete_config() {
438
		return \Jetpack_Options::delete_raw_option( 'jetpack_sync_full_config' );
439
	}
440
441
	private function get_config() {
442
		return \Jetpack_Options::get_raw_option( 'jetpack_sync_full_config' );
443
	}
444
445
	private function write_option( $name, $value ) {
446
		// we write our own option updating code to bypass filters/caching/etc on set_option/get_option
447
		global $wpdb;
448
		$serialized_value = maybe_serialize( $value );
449
		// try updating, if no update then insert
450
		// TODO: try to deal with the fact that unchanged values can return updated_num = 0
451
		// below we used "insert ignore" to at least suppress the resulting error
452
		$updated_num = $wpdb->query(
453
			$wpdb->prepare(
454
				"UPDATE $wpdb->options SET option_value = %s WHERE option_name = %s",
455
				$serialized_value,
456
				$name
457
			)
458
		);
459
460
		if ( ! $updated_num ) {
461
			$updated_num = $wpdb->query(
462
				$wpdb->prepare(
463
					"INSERT IGNORE INTO $wpdb->options ( option_name, option_value, autoload ) VALUES ( %s, %s, 'no' )",
464
					$name,
465
					$serialized_value
466
				)
467
			);
468
		}
469
		return $updated_num;
470
	}
471
472
	private function read_option( $name, $default = null ) {
473
		global $wpdb;
474
		$value = $wpdb->get_var(
475
			$wpdb->prepare(
476
				"SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1",
477
				$name
478
			)
479
		);
480
		$value = maybe_unserialize( $value );
481
482
		if ( $value === null && $default !== null ) {
483
			return $default;
484
		}
485
486
		return $value;
487
	}
488
}
489