Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
80.28% covered (warning)
80.28%
57 / 71
66.67% covered (warning)
66.67%
4 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
Performance_History_Entry
80.28% covered (warning)
80.28%
57 / 71
66.67% covered (warning)
66.67%
4 / 6
34.01
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get
52.00% covered (warning)
52.00%
13 / 25
0.00% covered (danger)
0.00%
0 / 1
12.42
 get_older_history
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
3
 get_older_window_periods
90.91% covered (success)
90.91%
20 / 22
0.00% covered (danger)
0.00%
0 / 1
12.11
 clear_cache
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 set
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2namespace Automattic\Jetpack_Boost\Data_Sync;
3
4use Automattic\Jetpack\Boost_Core\Lib\Transient;
5use Automattic\Jetpack\Boost_Speed_Score\Speed_Score_Graph_History_Request;
6use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Get;
7use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Entry_Can_Set;
8use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Lazy_Entry;
9use Automattic\Jetpack_Boost\Lib\Connection;
10
11class Performance_History_Entry implements Lazy_Entry, Entry_Can_Get, Entry_Can_Set {
12    /**
13     * How many older windows one request may ask about. Kept in step with
14     * olderWindowLimit in _inc/overview/lib/use-history-range.ts.
15     */
16    private const OLDER_WINDOW_LIMIT = 6;
17
18    /**
19     * Daily recording only lands scores in windows that end today, so an older window keeps
20     * whatever it holds until this expiry passes or Connection::register() clears the cache.
21     */
22    private const OLDER_WINDOW_TTL = 12 * 60 * 60;
23
24    private const CACHE_PREFIX = 'older_history_';
25
26    private $start_date;
27    private $end_date;
28    private $surface_errors = false;
29    private $older_windows  = array();
30
31    public function __construct() {
32        // Default to the last 30 days
33        $this->start_date = ( time() - 60 * 60 * 24 * 30 ) * 1000;
34        $this->end_date   = time() * 1000;
35    }
36
37    public function get( $_fallback = false ) {
38        if ( $this->older_windows ) {
39            return $this->get_older_history();
40        }
41
42        $request = new Speed_Score_Graph_History_Request( $this->start_date, $this->end_date, array() );
43        $result  = $request->execute();
44
45        if ( is_wp_error( $result ) && $this->surface_errors ) {
46            throw new \RuntimeException( $result->get_error_message() );
47        }
48
49        if ( is_wp_error( $result ) || empty( $result['data'] ) ) {
50            return array(
51                'startDate'   => $this->start_date,
52                'endDate'     => $this->end_date,
53                'periods'     => array(),
54                'annotations' => array(),
55            );
56        }
57
58        $annotations = $result['data']['annotations'] ?? array();
59        // Sanitize the annotations
60        foreach ( $annotations as $key => $annotation ) {
61            $annotations[ $key ] = array(
62                'timestamp' => $annotation['timestamp'],
63                'text'      => wp_kses_post( $annotation['text'] ),
64            );
65        }
66
67        return array(
68            'startDate'   => $result['data']['_meta']['start'],
69            'endDate'     => $result['data']['_meta']['end'],
70            'periods'     => $result['data']['periods'],
71            'annotations' => $annotations,
72        );
73    }
74
75    private function get_older_history() {
76        $history = array(
77            'startDate'   => $this->start_date,
78            'endDate'     => $this->end_date,
79            'periods'     => array(),
80            'annotations' => array(),
81        );
82
83        foreach ( $this->older_windows as $window ) {
84            $periods = $this->get_older_window_periods( $window );
85            if ( $periods ) {
86                $history['periods'] = $periods;
87                break;
88            }
89        }
90
91        return $history;
92    }
93
94    private function get_older_window_periods( $window ) {
95        $cache_key = self::CACHE_PREFIX . md5( wp_json_encode( array( Connection::wpcom_blog_id(), $window ), JSON_UNESCAPED_SLASHES ) );
96        $cached    = Transient::get( $cache_key );
97        if ( null !== $cached ) {
98            return $cached;
99        }
100
101        $request = new Speed_Score_Graph_History_Request( $window['startDate'], $window['endDate'], array() );
102        $result  = $request->execute();
103        if ( is_wp_error( $result ) ) {
104            throw new \RuntimeException( $result->get_error_message() );
105        }
106
107        // A response without history reads as an empty window, matching the single-window path above.
108        $data = $result['data'] ?? array();
109        if ( ! is_array( $data ) || ( array() !== $data && ! isset( $data['periods'] ) ) ) {
110            throw new \RuntimeException( 'Invalid performance history response.' );
111        }
112        $periods = $data['periods'] ?? array();
113        if ( ! is_array( $periods ) ) {
114            throw new \RuntimeException( 'Invalid performance history periods.' );
115        }
116
117        $found = array();
118        foreach ( $periods as $period ) {
119            if ( ! isset( $period['timestamp'] ) || ! is_numeric( $period['timestamp'] ) ) {
120                throw new \RuntimeException( 'Invalid performance history timestamp.' );
121            }
122            if ( $period['timestamp'] >= $window['startDate'] && $period['timestamp'] <= $window['endDate'] ) {
123                $found[] = $period;
124            }
125        }
126
127        Transient::set( $cache_key, $found, self::OLDER_WINDOW_TTL );
128        return $found;
129    }
130
131    /**
132     * Forget every cached older window, for when registering the site alters what history exists.
133     */
134    public static function clear_cache() {
135        Transient::delete_by_prefix( self::CACHE_PREFIX );
136    }
137
138    public function set( $value ) {
139        $older_windows = $value['olderWindows'] ?? array();
140        if ( true === ( $value['checkOlderWindows'] ?? false ) && ! $older_windows ) {
141            throw new \RuntimeException( 'Older history windows are missing or malformed.' );
142        }
143        if ( count( $older_windows ) > self::OLDER_WINDOW_LIMIT ) {
144            throw new \RuntimeException( 'At most ' . self::OLDER_WINDOW_LIMIT . ' older history windows are supported.' );
145        }
146
147        $this->start_date     = $value['startDate'];
148        $this->end_date       = $value['endDate'];
149        $this->surface_errors = true === ( $value['surfaceErrors'] ?? false );
150        $this->older_windows  = $older_windows;
151    }
152}