Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
74.50% covered (warning)
74.50%
111 / 149
72.22% covered (warning)
72.22%
13 / 18
CRAP
0.00% covered (danger)
0.00%
0 / 1
Speed_Score_Request
74.83% covered (warning)
74.83%
110 / 147
72.22% covered (warning)
72.22%
13 / 18
84.74
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 generate_cache_id_from_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 canonicalize_url
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_active_modules
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_created
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_poll_gap
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_cloud_progress
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 sanitize_cloud_progress
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
10.08
 jsonSerialize
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 jsonUnserialize
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
5.01
 cache_prefix
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 execute
77.78% covered (warning)
77.78%
14 / 18
0.00% covered (danger)
0.00%
0 / 1
3.10
 is_pending
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_error
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_success
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 poll_update
58.97% covered (warning)
58.97%
23 / 39
0.00% covered (danger)
0.00%
0 / 1
12.42
 restart
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 record_history
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
6
1<?php
2/**
3 * Represents a request to generate a pair of speed scores.
4 *
5 * @package automattic/jetpack-boost-speed-score
6 */
7
8namespace Automattic\Jetpack\Boost_Speed_Score;
9
10use Automattic\Jetpack\Boost_Core\Lib\Boost_API;
11use Automattic\Jetpack\Boost_Core\Lib\Cacheable;
12use Automattic\Jetpack\Boost_Core\Lib\Url;
13
14if ( ! defined( 'ABSPATH' ) ) {
15    exit( 0 );
16}
17
18/**
19 * Class Speed_Score_Request
20 */
21class Speed_Score_Request extends Cacheable {
22    /**
23     * Algorithm to use when defining a hash for the cache.
24     */
25    const CACHE_KEY_HASH_ALGO = 'md5';
26
27    /**
28     * The URL to get the Speed Scores for.
29     *
30     * @var string $url Url to get the Speed Scores for.
31     */
32    private $url;
33
34    /**
35     * Active Jetpack Boost modules.
36     *
37     * @var string[] $active_modules Active modules.
38     */
39    private $active_modules;
40
41    /**
42     * When the Speed Scores request was created, in seconds since epoch.
43     *
44     * @var int|float $created Speed Scores request creation timestamp.
45     */
46    private $created;
47
48    /**
49     * Current status of the Speed Score request.
50     *
51     * @var string $status Speed Scores request status.
52     */
53    private $status;
54
55    /**
56     * Number of retries attempted.
57     *
58     * @var int $retry_count Number of times this Speed Score request has been retried.
59     */
60    private $retry_count;
61
62    /**
63     * When this request was last polled, in seconds since epoch.
64     *
65     * @var int|float|null $last_polled Last poll timestamp, or null before the first poll.
66     */
67    private $last_polled;
68
69    /**
70     * Seconds between this poll and the one before it (or the dispatch), set by poll_update().
71     *
72     * @var float|null $poll_gap Gap in seconds, or null when not polled in this request.
73     */
74    private $poll_gap;
75
76    /**
77     * Progress Boost Cloud reported while the request runs: `stage`, `scores` and `estimatedSeconds`, each when known.
78     *
79     * @var array $cloud_progress Sanitized cloud progress.
80     */
81    private $cloud_progress = array();
82
83    /**
84     * The error returned
85     *
86     * @var array $error Speed Scores error.
87     */
88    private $error;
89
90    /**
91     * Where the Speed Scores request was made from.
92     *
93     * @var string $client A string passed to Speed_Score to identify where the request was made from.
94     */
95    private $client;
96
97    /**
98     * Constructor.
99     *
100     * @param string         $url The URL to get the Speed Scores for.
101     * @param array          $active_modules Active modules.
102     * @param int|float|null $created When the Speed Scores request was created, in seconds since epoch.
103     * @param string         $status Status of the Speed Scores request.
104     * @param null           $error The Speed Scores error.
105     * @param string         $client A string identifying where the request was made from.
106     */
107    public function __construct( $url, $active_modules = array(), $created = null, $status = 'pending', $error = null, $client = null ) {
108        $this->set_cache_id( self::generate_cache_id_from_url( $url ) );
109
110        $this->url            = $url;
111        $this->active_modules = $active_modules;
112        $this->created        = $created === null ? microtime( true ) : $created;
113        $this->status         = $status;
114        $this->error          = $error;
115        $this->client         = $client;
116        $this->retry_count    = 0;
117    }
118
119    /**
120     * Generate the cache ID from the URL.
121     *
122     * @param string $url The URL to get the Speed Scores for.
123     *
124     * @return string
125     */
126    public static function generate_cache_id_from_url( $url ) {
127        return hash( self::CACHE_KEY_HASH_ALGO, self::canonicalize_url( $url ) );
128    }
129
130    /**
131     * Remove trailing path slashes while preserving the query string and fragment.
132     *
133     * Url::normalize() is no use here: it also removes the query argument that keeps the
134     * "without Boost" scores apart from the regular ones.
135     *
136     * @param string $url The URL.
137     *
138     * @return string
139     */
140    private static function canonicalize_url( $url ) {
141        $path_length = strcspn( $url, '?#' );
142
143        return rtrim( substr( $url, 0, $path_length ), '/' ) . substr( $url, $path_length );
144    }
145
146    /**
147     * Get the list of active performance modules while this request was created.
148     *
149     * @return string[]
150     */
151    public function get_active_modules() {
152        return $this->active_modules;
153    }
154
155    /**
156     * When this request was dispatched, or last restarted.
157     *
158     * @return int|float Seconds since epoch.
159     */
160    public function get_created() {
161        return $this->created;
162    }
163
164    /**
165     * Seconds between the latest poll and the one before it, or null when not polled in this request.
166     *
167     * @return float|null
168     */
169    public function get_poll_gap() {
170        return $this->poll_gap;
171    }
172
173    /**
174     * Progress Boost Cloud last reported for this request.
175     *
176     * @return array `stage` (queued, mobile or desktop), `scores` (finished devices) and `estimatedSeconds`, each when known.
177     */
178    public function get_cloud_progress() {
179        return $this->cloud_progress;
180    }
181
182    /**
183     * Keep only the progress fields the dashboard understands, in the shapes it expects.
184     *
185     * @param mixed $response A WordPress.com response, or stored progress.
186     *
187     * @return array
188     */
189    private static function sanitize_cloud_progress( $response ) {
190        $progress = array();
191        if ( ! is_array( $response ) ) {
192            return $progress;
193        }
194
195        if ( isset( $response['stage'] ) && in_array( $response['stage'], array( 'queued', 'mobile', 'desktop' ), true ) ) {
196            $progress['stage'] = $response['stage'];
197        }
198
199        foreach ( array( 'mobile', 'desktop' ) as $device ) {
200            if ( isset( $response['scores'][ $device ] ) && is_numeric( $response['scores'][ $device ] ) ) {
201                $progress['scores'][ $device ] = max( 0, min( 100, (int) $response['scores'][ $device ] ) );
202            }
203        }
204
205        if ( isset( $response['estimatedSeconds'] ) && is_numeric( $response['estimatedSeconds'] ) && (int) $response['estimatedSeconds'] > 0 ) {
206            $progress['estimatedSeconds'] = (int) $response['estimatedSeconds'];
207        }
208
209        return $progress;
210    }
211
212    /**
213     * Convert this object to a plain array for JSON serialization.
214     */
215    #[\ReturnTypeWillChange]
216    public function jsonSerialize() {
217        return array(
218            'id'             => $this->get_cache_id(),
219            'url'            => $this->url,
220            'active_modules' => $this->get_active_modules(),
221            'created'        => $this->created,
222            'status'         => $this->status,
223            'error'          => $this->error,
224            'client'         => $this->client,
225            'retry_count'    => $this->retry_count,
226            'last_polled'    => $this->last_polled,
227            'cloud_progress' => $this->cloud_progress,
228        );
229    }
230
231    /**
232     * This is intended to be the reverse of JsonSerializable->jsonSerialize.
233     *
234     * @param mixed $data The data to turn into an object.
235     *
236     * @return Speed_Score_Request
237     */
238    public static function jsonUnserialize( $data ) {
239        $object = new Speed_Score_Request(
240            $data['url'],
241            $data['active_modules'],
242            $data['created'],
243            $data['status'],
244            $data['error'],
245            $data['client']
246        );
247
248        if ( ! empty( $data['id'] ) ) {
249            $object->set_cache_id( $data['id'] );
250        }
251
252        if ( ! empty( $data['retry_count'] ) ) {
253            $object->retry_count = intval( $data['retry_count'] );
254        }
255
256        if ( ! empty( $data['last_polled'] ) ) {
257            $object->last_polled = $data['last_polled'];
258        }
259
260        if ( ! empty( $data['cloud_progress'] ) ) {
261            $object->cloud_progress = self::sanitize_cloud_progress( $data['cloud_progress'] );
262        }
263
264        return $object;
265    }
266
267    /**
268     * Return the cache prefix.
269     *
270     * @return string
271     */
272    protected static function cache_prefix() {
273        return 'jetpack_boost_speed_scores_';
274    }
275
276    /**
277     * Send a Speed Scores request to the API.
278     *
279     * @return true|\WP_Error True on success, WP_Error on failure.
280     */
281    public function execute() {
282        $response = Boost_API::post(
283            'speed-scores',
284            array(
285                'request_id'     => $this->get_cache_id(),
286                'url'            => Url::normalize( $this->url ),
287                'active_modules' => $this->active_modules,
288                'client'         => $this->client,
289            )
290        );
291
292        if ( is_wp_error( $response ) ) {
293            $this->status = 'error';
294            $this->error  = $response->get_error_message();
295            $this->store();
296
297            return $response;
298        }
299
300        // WordPress.com answers with the queued stage and, when it has one, Boost Cloud's estimate.
301        $this->cloud_progress = self::sanitize_cloud_progress( $response );
302        if ( $this->cloud_progress ) {
303            $this->store( 3600 );
304        }
305
306        return true;
307    }
308
309    /**
310     * Is this request pending?
311     */
312    public function is_pending() {
313        return 'pending' === $this->status;
314    }
315
316    /**
317     * Did the request fail?
318     */
319    public function is_error() {
320        return 'error' === $this->status;
321    }
322
323    /**
324     * Did the request succeed?
325     */
326    public function is_success() {
327        return 'success' === $this->status;
328    }
329
330    /**
331     * Poll for updates to this Speed Scores request.
332     *
333     * @return true|\WP_Error True on success, WP_Error on failure.
334     */
335    public function poll_update() {
336        $now               = microtime( true );
337        $this->poll_gap    = $now - ( $this->last_polled ?? $this->created );
338        $this->last_polled = $now;
339
340        $response = Boost_API::get(
341            sprintf(
342                'speed-scores/%s',
343                $this->get_cache_id()
344            )
345        );
346
347        if ( is_wp_error( $response ) ) {
348            // Special case: If the request is not found, restart it.
349            if ( 'not_found' === $response->get_error_code() ) {
350                return $this->restart();
351            }
352
353            return $response;
354        }
355
356        switch ( $response['status'] ) {
357            case 'pending':
358                // The initial job probably failed, dispatch again if so.
359                if ( $this->created <= strtotime( '-15 mins' ) ) {
360                    return $this->restart();
361                }
362                $this->cloud_progress = self::sanitize_cloud_progress( $response );
363                // As long as WordPress.com keeps the result; the default would drop a run the user left mid-way.
364                $this->store( 3600 );
365                break;
366
367            case 'error':
368                $this->status = 'error';
369                $this->error  = $response['error'];
370                $this->store();
371                break;
372
373            case 'success':
374                $this->status = 'success';
375                $this->store();
376                $this->record_history( $response );
377
378                break;
379
380            default:
381                return new \WP_Error(
382                    'invalid_response',
383                    __(
384                        'Invalid response from WPCOM API while polling for speed scores',
385                        'jetpack-boost-speed-score'
386                    ),
387                    $response
388                );
389        }
390
391        return true;
392    }
393
394    /**
395     * Restart this request; useful when WPCOM doesn't recognize the request or it times out.
396     */
397    private function restart() {
398        // Enforce a maximum number of restarts.
399        if ( $this->retry_count > 2 ) {
400            $this->status = 'error';
401            $this->error  = 'Maximum number of retries exceeded';
402            $this->store();
403
404            return new \WP_Error(
405                'error',
406                $this->error
407            );
408        }
409
410        $result = $this->execute();
411        if ( is_wp_error( $result ) ) {
412            return $result;
413        }
414
415        $this->created = time();
416        ++$this->retry_count;
417        $this->store();
418
419        return true;
420    }
421
422    /**
423     * Save the speed score record to history.
424     *
425     * @param array $response Response from api.
426     */
427    private function record_history( $response ) {
428        $history       = new Speed_Score_History( $this->url );
429        $last_history  = $history->latest();
430        $last_scores   = $last_history ? $last_history['scores'] : null;
431        $last_theme    = $last_history['theme'] ?? null; // Entries saved before the theme was recorded have no theme key.
432        $current_theme = wp_get_theme()->get( 'Name' );
433
434        // Scores describe the site as it stood when the run was dispatched, so judge staleness
435        // against that instant.
436        $measured_current_site = $this->created >= Speed_Score_History::get_stale_timestamp();
437
438        // Only change if there is a difference from last score or the theme changed.
439        if ( $last_scores !== $response['scores'] || $current_theme !== $last_theme ) {
440            $history->push(
441                array(
442                    'timestamp' => $measured_current_site ? time() : (int) $this->created,
443                    'scores'    => $response['scores'],
444                    'theme'     => $current_theme,
445                )
446            );
447        } elseif ( $measured_current_site ) {
448            $history->touch_latest();
449        }
450    }
451}