|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/* |
| 6 | + * This file is part of Ymir WordPress plugin. |
| 7 | + * |
| 8 | + * (c) Carl Alexander <[email protected]> |
| 9 | + * |
| 10 | + * For the full copyright and license information, please view the LICENSE |
| 11 | + * file that was distributed with this source code. |
| 12 | + */ |
| 13 | + |
| 14 | +namespace Ymir\Plugin\CloudProvider\Aws; |
| 15 | + |
| 16 | +use Ymir\Plugin\Http\Client; |
| 17 | +use Ymir\Plugin\PageCache\ContentDeliveryNetworkPageCacheClientInterface; |
| 18 | +use Ymir\Plugin\Support\Collection; |
| 19 | + |
| 20 | +/** |
| 21 | + * The client for AWS CloudFront API. |
| 22 | + */ |
| 23 | +class CloudFrontClient extends AbstractClient implements ContentDeliveryNetworkPageCacheClientInterface |
| 24 | +{ |
| 25 | + /** |
| 26 | + * The ID of the CloudFront distribution. |
| 27 | + * |
| 28 | + * @var string |
| 29 | + */ |
| 30 | + private $distributionId; |
| 31 | + |
| 32 | + /** |
| 33 | + * All the paths that we want to invalidate. |
| 34 | + * |
| 35 | + * @var array |
| 36 | + */ |
| 37 | + private $invalidationPaths; |
| 38 | + |
| 39 | + /** |
| 40 | + * {@inheritdoc} |
| 41 | + */ |
| 42 | + public function __construct(Client $client, string $distributionId, string $key, string $secret) |
| 43 | + { |
| 44 | + parent::__construct($client, $key, 'us-east-1', $secret); |
| 45 | + |
| 46 | + $this->distributionId = $distributionId; |
| 47 | + $this->invalidationPaths = []; |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * {@inheritdoc} |
| 52 | + */ |
| 53 | + public function clearAll() |
| 54 | + { |
| 55 | + $this->addPath('/*'); |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * {@inheritdoc} |
| 60 | + */ |
| 61 | + public function clearUrl(string $url) |
| 62 | + { |
| 63 | + $path = parse_url($url, PHP_URL_PATH); |
| 64 | + |
| 65 | + if (false === $path) { |
| 66 | + throw new \RuntimeException(sprintf('Unable to parse URL: %s', $url)); |
| 67 | + } |
| 68 | + |
| 69 | + $this->addPath('/'.ltrim((string) $path, '/')); |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * {@inheritdoc} |
| 74 | + */ |
| 75 | + public function sendClearRequest() |
| 76 | + { |
| 77 | + if (empty($this->invalidationPaths)) { |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + $this->createInvalidation($this->invalidationPaths); |
| 82 | + |
| 83 | + $this->invalidationPaths = []; |
| 84 | + } |
| 85 | + |
| 86 | + /** |
| 87 | + * {@inheritdoc} |
| 88 | + */ |
| 89 | + protected function getHostname(): string |
| 90 | + { |
| 91 | + return 'cloudfront.amazonaws.com'; |
| 92 | + } |
| 93 | + |
| 94 | + /** |
| 95 | + * {@inheritdoc} |
| 96 | + */ |
| 97 | + protected function getService(): string |
| 98 | + { |
| 99 | + return 'cloudfront'; |
| 100 | + } |
| 101 | + |
| 102 | + /** |
| 103 | + * Add the given path to the list. |
| 104 | + */ |
| 105 | + private function addPath(string $path) |
| 106 | + { |
| 107 | + if (in_array($path, ['*', '/*'])) { |
| 108 | + $this->invalidationPaths = ['/*']; |
| 109 | + } |
| 110 | + |
| 111 | + if (['/*'] === $this->invalidationPaths) { |
| 112 | + return; |
| 113 | + } |
| 114 | + |
| 115 | + $this->invalidationPaths[] = $path; |
| 116 | + } |
| 117 | + |
| 118 | + /** |
| 119 | + * Create an invalidation request. |
| 120 | + */ |
| 121 | + private function createInvalidation($paths) |
| 122 | + { |
| 123 | + if (is_string($paths)) { |
| 124 | + $paths = [$paths]; |
| 125 | + } elseif (!is_array($paths)) { |
| 126 | + throw new \InvalidArgumentException('"paths" argument must be an array or a string'); |
| 127 | + } |
| 128 | + |
| 129 | + if (count($paths) > 1) { |
| 130 | + $paths = $this->filterUniquePaths($paths); |
| 131 | + } |
| 132 | + |
| 133 | + $response = $this->request('post', "/2020-05-31/distribution/{$this->distributionId}/invalidation", $this->generateInvalidationPayload($paths)); |
| 134 | + |
| 135 | + if (201 !== $this->parseResponseStatusCode($response)) { |
| 136 | + throw new \RuntimeException('Invalidation request failed'); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + /** |
| 141 | + * Filter all paths and only keep unique ones. |
| 142 | + */ |
| 143 | + private function filterUniquePaths(array $paths): array |
| 144 | + { |
| 145 | + $paths = (new Collection($paths))->unique(); |
| 146 | + |
| 147 | + $filteredPaths = $paths->filter(function (string $path) { |
| 148 | + return '*' !== substr($path, -1); |
| 149 | + })->all(); |
| 150 | + $wildcardPaths = $paths->filter(function (string $path) { |
| 151 | + return '*' === substr($path, -1); |
| 152 | + }); |
| 153 | + |
| 154 | + $wildcardPaths = $wildcardPaths->map(function (string $path) use ($wildcardPaths) { |
| 155 | + $filteredWildcardPaths = preg_grep(sprintf('/%s/', str_replace('\*', '.*', preg_quote($path, '/'))), $wildcardPaths->all(), PREG_GREP_INVERT); |
| 156 | + $filteredWildcardPaths[] = $path; |
| 157 | + |
| 158 | + return $filteredWildcardPaths; |
| 159 | + }); |
| 160 | + |
| 161 | + $wildcardPaths = new Collection(array_intersect(...$wildcardPaths->all())); |
| 162 | + |
| 163 | + if ($wildcardPaths->count() > 15) { |
| 164 | + throw new \RuntimeException('CloudFront only allows for a maximum of 15 wildcard invalidations'); |
| 165 | + } |
| 166 | + |
| 167 | + $wildcardPaths->each(function (string $path) use (&$filteredPaths) { |
| 168 | + $filteredPaths = preg_grep(sprintf('/%s/', str_replace('\*', '.*', preg_quote($path, '/'))), $filteredPaths, PREG_GREP_INVERT); |
| 169 | + }); |
| 170 | + |
| 171 | + return array_merge($wildcardPaths->all(), $filteredPaths); |
| 172 | + } |
| 173 | + |
| 174 | + /** |
| 175 | + * Generate a unique caller reference. |
| 176 | + */ |
| 177 | + private function generateCallerReference(): string |
| 178 | + { |
| 179 | + $length = 16; |
| 180 | + $reference = ''; |
| 181 | + |
| 182 | + while (strlen($reference) < $length) { |
| 183 | + $size = $length - strlen($reference); |
| 184 | + |
| 185 | + $bytes = random_bytes($size); |
| 186 | + |
| 187 | + $reference .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size); |
| 188 | + } |
| 189 | + |
| 190 | + return $reference.'-'.time(); |
| 191 | + } |
| 192 | + |
| 193 | + /** |
| 194 | + * Generate the XML payload for an invalidation request. |
| 195 | + */ |
| 196 | + private function generateInvalidationPayload(array $paths): string |
| 197 | + { |
| 198 | + $xmlDocument = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/"></InvalidationBatch>'); |
| 199 | + |
| 200 | + $xmlDocument->addChild('CallerReference', $this->generateCallerReference()); |
| 201 | + |
| 202 | + $pathsNode = $xmlDocument->addChild('Paths'); |
| 203 | + $itemsNode = $pathsNode->addChild('Items'); |
| 204 | + |
| 205 | + foreach ($paths as $path) { |
| 206 | + $itemsNode->addChild('Path', $path); |
| 207 | + } |
| 208 | + |
| 209 | + $pathsNode->addChild('Quantity', (string) count($paths)); |
| 210 | + |
| 211 | + $xml = $xmlDocument->asXML(); |
| 212 | + |
| 213 | + if (!is_string($xml)) { |
| 214 | + throw new \RuntimeException('Unable to generate invalidation XML payload'); |
| 215 | + } |
| 216 | + |
| 217 | + return $xml; |
| 218 | + } |
| 219 | +} |
0 commit comments