Skip to content

Commit

Permalink
Purge Cloudflare cache for all files after uploading R2 artifacts (#3568
Browse files Browse the repository at this point in the history
)

If an attempt to access R2 artifacts is made before the files exist, the 404
reply gets cached and it's not possible to access the file after it's been
created without purging the cache, essentially doing a cache poisoning for
future build artifacts. To avoid it, list all files that have been created by
the build and call the purge cache API.

As there's a limit for number of files that can be purged in a single API call
[1], the GNU split utility is used to split intermediary list of files to
chunks of 30 URLs, which is then converted to a JSON array and passed to the
curl command.

[1] https://developers.cloudflare.com/api/operations/zone-purge#purge-cached-content-by-url
  • Loading branch information
sairon authored Sep 2, 2024
1 parent b23b54b commit d9e46d6
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions .github/workflows/artifacts-index.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,20 @@ jobs:
- name: Flush CloudFlare cache
run: |
curl --silent --show-error --fail -X POST \
"https://api.cloudflare.com/client/v4/zones/${{ secrets.CF_ZONE }}/purge_cache" \
-H "Authorization: Bearer ${{ secrets.CF_PURGE_TOKEN }}" \
-H "Content-Type: application/json" \
--data '{"files": [
"https://os-artifacts.home-assistant.io/index.html",
"https://os-artifacts.home-assistant.io/index.json"
] }'
# Create purge list of all artifacts
jq -r '. | map("https://os-artifacts.home-assistant.io/${{ inputs.version }}/" + .) | join("\n")' < "${{ inputs.version }}.json" > purge_list
# Add indexes to purge list too
echo "https://os-artifacts.home-assistant.io/indexes/${{ inputs.version }}.json" >> purge_list
echo "https://os-artifacts.home-assistant.io/index.html" >> purge_list
echo "https://os-artifacts.home-assistant.io/index.json" >> purge_list
# Split to chunks of 30 files (limit of CF API)
split -d -l30 purge_list purge_list_chunked
# Convert chunked lists to JSON arrays and call CF purge API
for f in purge_list_chunked*; do
files=$(jq -R -s 'split("\n")[:-1]' < "$f")
curl --silent --show-error --fail -X POST \
"https://api.cloudflare.com/client/v4/zones/${{ secrets.CF_ZONE }}/purge_cache" \
-H "Authorization: Bearer ${{ secrets.CF_PURGE_TOKEN }}" \
-H "Content-Type: application/json" \
--data "{\"files\": ${files}}"
done

0 comments on commit d9e46d6

Please sign in to comment.