Skip to content

Commit 475e3e6

Browse files
authored
add custom plugin to rewrite GU responses to fastly cache (#78)
1 parent 76c416a commit 475e3e6

2 files changed

Lines changed: 65 additions & 8 deletions

File tree

composer.lock

Lines changed: 8 additions & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
/**
3+
* Plugin Name: FAIR Server - Git Updater Filter
4+
* Description: Filter GU output to rewrite download urls
5+
* Network: true
6+
*/
7+
8+
namespace FAIRServer\GUFilter;
9+
10+
add_filter('rest_pre_echo_response', __NAMESPACE__ . '\\rewrite_gu_response');
11+
12+
function rewrite_gu_response($response)
13+
{
14+
$download_link = $response['download_link'] ?? null;
15+
16+
if (!$download_link || !str_contains($download_link, 'fairpm/fair-plugin')) {
17+
return $response;
18+
}
19+
20+
$versions = $response['versions'] ?? null;
21+
if (!$versions) {
22+
error_log('WARNING: response contained download_link for fair-plugin but no versions: '
23+
. print_r($response, true));
24+
return $response;
25+
}
26+
27+
$version = array_flip($versions)[$download_link] ?? null;
28+
if (!$version) {
29+
error_log('WARNING: download_link not contained in versions: ' . print_r($versions, true));
30+
return $response;
31+
}
32+
33+
// This is hairier than usual because 404 responses get cached longer than they ought to be
34+
35+
$mirror_url = "https://download.fair.pm/release/fair-connect-$version.zip";
36+
$busted = null;
37+
$key = "mirror_url:$mirror_url";
38+
39+
$status = get_transient($key);
40+
if (!$status) {
41+
$status = wp_remote_retrieve_response_code(wp_safe_remote_head($mirror_url));
42+
if ((int)$status === 404) {
43+
// 404 responses are cached for a while, so try again with a cachebuster
44+
$busted = $mirror_url . '?' . time();
45+
$status = wp_remote_retrieve_response_code(wp_safe_remote_head($busted));
46+
}
47+
set_transient($key, $status, 300); // cache for 5 minutes (which is way less time than 404s are being cached)
48+
}
49+
50+
if ((int)$status !== 200) {
51+
error_log(__FUNCTION__ . ": HEAD on $mirror_url returned status $status");
52+
return $response;
53+
}
54+
55+
$response['download_link'] = $busted ?? $mirror_url;
56+
return $response;
57+
}

0 commit comments

Comments
 (0)