Skip to content

Commit ba91ab7

Browse files
authored
Backup: Cache the storage and plan reads for five minutes (#55207)
* Backup: Cache the storage and plan reads for five minutes The Backup page asked WordPress.com for capabilities, size and policies on every visit. Keep a good answer in a transient for five minutes, keep a capabilities answer only when it includes Backup, and drop the storage figures after a retention change or a return from storage checkout. * Backup: Keep storage reads out of the cache right after checkout A purchase can take a moment to reach the storage policy, so the reads made on the return from checkout are not cached for the next five minutes. Also cover a refused retention update and the policies cache in the retention test.
1 parent dfd77f4 commit ba91ab7

15 files changed

Lines changed: 301 additions & 36 deletions

File tree

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Significance: patch
2+
Type: changed
3+
4+
Cache the storage figures and plan check for five minutes, so returning to the Backup page asks WordPress.com less.

‎projects/packages/backup/src/class-jetpack-backup.php‎

Lines changed: 89 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,48 @@ class Jetpack_Backup {
103103
*/
104104
const PROMOTED_PRODUCT_CACHE_TTL = 12 * HOUR_IN_SECONDS;
105105

106+
/**
107+
* Transient holding the last good `/rewind/size` answer.
108+
*
109+
* @var string
110+
*/
111+
const SITE_SIZE_TRANSIENT = 'jetpack_backup_site_size';
112+
113+
/**
114+
* Transient holding the last good `/rewind/policies` answer.
115+
*
116+
* @var string
117+
*/
118+
const SITE_POLICIES_TRANSIENT = 'jetpack_backup_site_policies';
119+
120+
/**
121+
* Transient that, while set, keeps the storage reads out of the cache.
122+
*
123+
* @var string
124+
*/
125+
const STORAGE_CACHE_BYPASS_TRANSIENT = 'jetpack_backup_storage_cache_bypass';
126+
127+
/**
128+
* Transient holding the dashboard's capabilities, kept only while they include Backup.
129+
*
130+
* @var string
131+
*/
132+
const CAPABILITIES_TRANSIENT = 'jetpack_backup_capabilities';
133+
134+
/**
135+
* How long a rewind read stays cached: the same window the dashboard already treats these reads as fresh.
136+
*
137+
* @var int
138+
*/
139+
const REWIND_READ_CACHE_TTL = 5 * MINUTE_IN_SECONDS;
140+
141+
/**
142+
* Query arg the dashboard's checkout links return with, so the storage figures are read again.
143+
*
144+
* @var string
145+
*/
146+
const STORAGE_PURCHASED_ARG = 'storage_purchased';
147+
106148
/**
107149
* Licenses product ID.
108150
*
@@ -296,6 +338,13 @@ public static function add_wp_admin_submenu() {
296338
public static function admin_init() {
297339
add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_admin_scripts' ) );
298340

341+
// Only bypasses a cache, so it needs no nonce.
342+
if ( isset( $_GET[ self::STORAGE_PURCHASED_ARG ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
343+
self::clear_storage_cache();
344+
// A purchase can take a moment to reach `/rewind/policies`, so a read made right after checkout is not kept.
345+
set_transient( self::STORAGE_CACHE_BYPASS_TRANSIENT, 1, self::REWIND_READ_CACHE_TTL );
346+
}
347+
299348
if ( self::is_wp_build_dashboard_active() ) {
300349
// Notices reflow the dual-pane layout, so clear them but keep our own.
301350
// An older jetpack-jitm may predate the helper; the fallback costs the JITM.
@@ -1048,25 +1097,7 @@ public static function manage_dismissed_backup_review_request( $request ) {
10481097
* @return \WP_REST_Response|WP_Error The site storage size, or a WP_Error if WordPress.com could not be reached.
10491098
*/
10501099
public static function get_site_backup_size() {
1051-
$blog_id = Jetpack_Options::get_option( 'id' );
1052-
1053-
$response = Client::wpcom_json_api_request_as_user(
1054-
'/sites/' . $blog_id . '/rewind/size?force=wpcom',
1055-
'v2',
1056-
array(),
1057-
null,
1058-
'wpcom'
1059-
);
1060-
1061-
$response_code = (int) wp_remote_retrieve_response_code( $response );
1062-
1063-
if ( 200 !== $response_code ) {
1064-
return self::get_failed_fetch_error( $response );
1065-
}
1066-
1067-
return rest_ensure_response(
1068-
json_decode( $response['body'], true )
1069-
);
1100+
return self::get_cached_rewind_read( 'size', self::SITE_SIZE_TRANSIENT );
10701101
}
10711102

10721103
/**
@@ -1075,10 +1106,40 @@ public static function get_site_backup_size() {
10751106
* @return \WP_REST_Response|WP_Error The site storage policies, or a WP_Error if WordPress.com could not be reached.
10761107
*/
10771108
public static function get_site_backup_policies() {
1109+
return self::get_cached_rewind_read( 'policies', self::SITE_POLICIES_TRANSIENT );
1110+
}
1111+
1112+
/**
1113+
* Forget the cached storage figures, after anything that changes them.
1114+
*
1115+
* @since $$next-version$$
1116+
*
1117+
* @return void
1118+
*/
1119+
public static function clear_storage_cache() {
1120+
delete_transient( self::SITE_SIZE_TRANSIENT );
1121+
delete_transient( self::SITE_POLICIES_TRANSIENT );
1122+
}
1123+
1124+
/**
1125+
* Read a `/rewind/<endpoint>` route as the user, answering from a transient while one is warm.
1126+
*
1127+
* @param string $endpoint The route under `/sites/<id>/rewind/`.
1128+
* @param string $transient The transient that holds a good answer.
1129+
* @return \WP_REST_Response|WP_Error The decoded answer, or a WP_Error if WordPress.com could not be reached.
1130+
*/
1131+
private static function get_cached_rewind_read( $endpoint, $transient ) {
1132+
$use_cache = false === get_transient( self::STORAGE_CACHE_BYPASS_TRANSIENT );
1133+
$cached = $use_cache ? get_transient( $transient ) : false;
1134+
1135+
if ( is_array( $cached ) ) {
1136+
return rest_ensure_response( $cached );
1137+
}
1138+
10781139
$blog_id = Jetpack_Options::get_option( 'id' );
10791140

10801141
$response = Client::wpcom_json_api_request_as_user(
1081-
'/sites/' . $blog_id . '/rewind/policies?force=wpcom',
1142+
'/sites/' . $blog_id . '/rewind/' . $endpoint . '?force=wpcom',
10821143
'v2',
10831144
array(),
10841145
null,
@@ -1091,9 +1152,14 @@ public static function get_site_backup_policies() {
10911152
return self::get_failed_fetch_error( $response );
10921153
}
10931154

1094-
return rest_ensure_response(
1095-
json_decode( $response['body'], true )
1096-
);
1155+
$body = json_decode( $response['body'], true );
1156+
1157+
// `ok: false` is WordPress.com failing to measure; caching it would hide the figures once it recovers.
1158+
if ( $use_cache && is_array( $body ) && false !== ( $body['ok'] ?? true ) ) {
1159+
set_transient( $transient, $body, self::REWIND_READ_CACHE_TTL );
1160+
}
1161+
1162+
return rest_ensure_response( $body );
10971163
}
10981164

10991165
/**

‎projects/packages/backup/src/dashboard/components/storage-space/checkout-url.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,15 @@ import { getProductCheckoutUrl } from '@automattic/jetpack-components';
1919
* @return The Calypso checkout URL.
2020
*/
2121
export function storageAddonCheckoutUrl( productSlug: string, siteSuffix: string ): string {
22-
return getProductCheckoutUrl( productSlug, siteSuffix, window.location.href, true );
22+
const here = new URL( window.location.href );
23+
here.searchParams.set( STORAGE_PURCHASED_ARG, '1' );
24+
25+
return getProductCheckoutUrl( productSlug, siteSuffix, here.toString(), true );
2326
}
2427

2528
/** Query args that carry a retention choice through checkout and back. */
2629
export const RETENTION_ARG = 'retention';
30+
// Also tells the server to drop its cached storage figures; `Jetpack_Backup::admin_init()` reads it.
2731
export const STORAGE_PURCHASED_ARG = 'storage_purchased';
2832

2933
/**

‎projects/packages/backup/src/js/components/Backups.jsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ const CompleteBackup = ( { latestTime, stats } ) => {
273273
href={ getProductCheckoutUrl(
274274
addonSlug,
275275
siteSlug,
276-
`${ adminUrl }admin.php?page=jetpack-backup`,
276+
`${ adminUrl }admin.php?page=jetpack-backup&storage_purchased=1`,
277277
true
278278
) }
279279
onClick={ trackUpgradeStorageClick }

‎projects/packages/backup/src/js/components/backup-storage-space/storage-addon-upsell-prompt/index.jsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ export const StorageAddonUpsellPrompt = ( { usageLevel } ) => {
6868
href={ getProductCheckoutUrl(
6969
addonSlug,
7070
siteSlug,
71-
`${ adminUrl }admin.php?page=jetpack-backup`,
71+
`${ adminUrl }admin.php?page=jetpack-backup&storage_purchased=1`,
7272
true
7373
) }
7474
onClick={ trackUpgradeStorageClick }

‎projects/packages/backup/src/js/components/backup-storage-space/storage-help-popover/index.jsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ const StorageHelpPopover = ( { className, forecastInDays } ) => {
4747
const storageUpgradeUrl = getProductCheckoutUrl(
4848
addonSlug,
4949
siteSlug,
50-
`${ adminUrl }admin.php?page=jetpack-backup`,
50+
`${ adminUrl }admin.php?page=jetpack-backup&storage_purchased=1`,
5151
true
5252
);
5353

‎projects/packages/backup/src/rest/class-capabilities-bridge.php‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
namespace Automattic\Jetpack\Backup\V0005\REST;
99

10+
use Automattic\Jetpack\Backup\V0005\Jetpack_Backup;
1011
use Automattic\Jetpack\Connection\Client;
1112
use WP_Error;
1213
use WP_REST_Server;
@@ -56,6 +57,11 @@ public static function get_capabilities() {
5657
return $blog_id;
5758
}
5859

60+
$cached = get_transient( Jetpack_Backup::CAPABILITIES_TRANSIENT );
61+
if ( is_array( $cached ) ) {
62+
return rest_ensure_response( $cached );
63+
}
64+
5965
$response = Client::wpcom_json_api_request_as_user(
6066
sprintf( '/sites/%d/rewind/capabilities', $blog_id ),
6167
'v2',
@@ -125,12 +131,16 @@ public static function get_capabilities() {
125131
}
126132

127133
$capabilities = $body['capabilities'];
128-
129-
return rest_ensure_response(
130-
array(
131-
'hasBackupPlan' => in_array( 'backup', $capabilities, true ),
132-
'hasScan' => in_array( 'scan', $capabilities, true ),
133-
)
134+
$projected = array(
135+
'hasBackupPlan' => in_array( 'backup', $capabilities, true ),
136+
'hasScan' => in_array( 'scan', $capabilities, true ),
134137
);
138+
139+
// A "no plan" answer is not kept: a reader back from buying one must not meet the upsell again.
140+
if ( $projected['hasBackupPlan'] ) {
141+
set_transient( Jetpack_Backup::CAPABILITIES_TRANSIENT, $projected, Jetpack_Backup::REWIND_READ_CACHE_TTL );
142+
}
143+
144+
return rest_ensure_response( $projected );
135145
}
136146
}

‎projects/packages/backup/src/rest/class-retention-bridge.php‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
namespace Automattic\Jetpack\Backup\V0005\REST;
99

10+
use Automattic\Jetpack\Backup\V0005\Jetpack_Backup;
1011
use Automattic\Jetpack\Connection\Client;
1112
use WP_Error;
1213
use WP_REST_Request;
@@ -75,6 +76,9 @@ public static function update_retention( WP_REST_Request $request ) {
7576
'wpcom'
7677
);
7778

79+
// Whatever the outcome: the dashboard re-reads `/site/backup/size` for `retention_days` either way.
80+
Jetpack_Backup::clear_storage_cache();
81+
7882
if ( is_wp_error( $response ) ) {
7983
return Rest_Controller::transport_error( $response, 'retention_update_failed' );
8084
}

‎projects/packages/backup/tests/php/Jetpack_Backup_Test.php‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,9 @@ protected function tearDown(): void {
108108
foreach ( array( 'en_US', $this->locale ) as $locale ) {
109109
delete_transient( Jetpack_Backup::PROMOTED_PRODUCT_TRANSIENT_PREFIX . sanitize_key( $locale ) );
110110
}
111+
Jetpack_Backup::clear_storage_cache();
112+
delete_transient( Jetpack_Backup::STORAGE_CACHE_BYPASS_TRANSIENT );
113+
unset( $_GET[ Jetpack_Backup::STORAGE_PURCHASED_ARG ] );
111114

112115
$this->wpcom_status = 200;
113116
$this->wpcom_body = '{}';
@@ -759,6 +762,95 @@ public static function provide_uncacheable_failures() {
759762
);
760763
}
761764

765+
/**
766+
* Every visit to the dashboard within the cache window costs WordPress.com one storage read.
767+
*
768+
* @param string $callback Name of the route callback.
769+
* @dataProvider provide_storage_reads
770+
*/
771+
#[DataProvider( 'provide_storage_reads' )]
772+
public function test_storage_read_serves_a_second_read_from_cache( $callback ) {
773+
$this->sign_in_as_connected_admin();
774+
$this->wpcom_body = '{"ok":true,"size":1024}';
775+
add_filter( 'pre_http_request', array( $this, 'mock_wpcom_response' ) );
776+
777+
call_user_func( array( Jetpack_Backup::class, $callback ) );
778+
$second = call_user_func( array( Jetpack_Backup::class, $callback ) );
779+
780+
$this->assertSame( 1, $this->http_requests, $callback );
781+
$this->assertSame( 1024, $second->get_data()['size'], $callback );
782+
}
783+
784+
/**
785+
* Neither a failure nor WordPress.com's own `ok: false` is kept.
786+
*
787+
* @param string $callback Name of the route callback.
788+
* @param int|string $status Status for the first response.
789+
* @param string $body Body for the first response.
790+
* @dataProvider provide_uncacheable_storage_reads
791+
*/
792+
#[DataProvider( 'provide_uncacheable_storage_reads' )]
793+
public function test_storage_read_does_not_cache_a_failure( $callback, $status, $body ) {
794+
$this->sign_in_as_connected_admin();
795+
$this->wpcom_status = $status;
796+
$this->wpcom_body = $body;
797+
add_filter( 'pre_http_request', array( $this, 'mock_wpcom_response' ) );
798+
799+
call_user_func( array( Jetpack_Backup::class, $callback ) );
800+
$this->wpcom_status = 200;
801+
$this->wpcom_body = '{"ok":true,"size":1024}';
802+
$recovered = call_user_func( array( Jetpack_Backup::class, $callback ) );
803+
804+
$this->assertSame( 2, $this->http_requests, $callback );
805+
$this->assertSame( 1024, $recovered->get_data()['size'], $callback );
806+
}
807+
808+
/**
809+
* A reader back from buying storage sees the new figures, and a read made before the purchase lands is not kept.
810+
*/
811+
public function test_returning_from_checkout_reads_storage_fresh() {
812+
$this->sign_in_as_connected_admin();
813+
add_filter( 'pre_http_request', array( $this, 'mock_wpcom_response' ) );
814+
Jetpack_Backup::get_site_backup_size();
815+
Jetpack_Backup::get_site_backup_policies();
816+
817+
$_GET[ Jetpack_Backup::STORAGE_PURCHASED_ARG ] = '1';
818+
Jetpack_Backup::admin_init();
819+
Jetpack_Backup::get_site_backup_size();
820+
Jetpack_Backup::get_site_backup_policies();
821+
822+
$this->assertSame( 4, $this->http_requests );
823+
$this->assertFalse( get_transient( Jetpack_Backup::SITE_SIZE_TRANSIENT ) );
824+
$this->assertFalse( get_transient( Jetpack_Backup::SITE_POLICIES_TRANSIENT ) );
825+
}
826+
827+
/**
828+
* The two cached storage reads.
829+
*
830+
* @return array[]
831+
*/
832+
public static function provide_storage_reads() {
833+
return array(
834+
'size' => array( 'get_site_backup_size' ),
835+
'policies' => array( 'get_site_backup_policies' ),
836+
);
837+
}
838+
839+
/**
840+
* Each storage read with each answer that must not be kept.
841+
*
842+
* @return array[]
843+
*/
844+
public static function provide_uncacheable_storage_reads() {
845+
$sets = array();
846+
foreach ( array( 'get_site_backup_size', 'get_site_backup_policies' ) as $callback ) {
847+
$sets[ "$callback, a non-200" ] = array( $callback, 503, '{}' );
848+
$sets[ "$callback, ok: false" ] = array( $callback, 200, '{"ok":false}' );
849+
$sets[ "$callback, unreadable" ] = array( $callback, 200, 'not json' );
850+
}
851+
return $sets;
852+
}
853+
762854
public function test_promoted_product_info_caches_per_locale() {
763855
add_filter( 'pre_http_request', array( $this, 'mock_request_as_product_catalogue' ), 10, 3 );
764856

0 commit comments

Comments
 (0)