Repository navigation
Expand file tree
/
Copy pathnix-cache-upload
More file actions
executable file
·423 lines (375 loc) · 17.2 KB
/
Copy pathnix-cache-upload
File metadata and controls
executable file
·423 lines (375 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
#!/usr/bin/env bash
# Publish a Nix closure through the cache's direct-to-R2 upload protocol.
# This script deliberately targets Bash 3.2 so it also works with the system
# Bash shipped by older macOS releases.
set -euo pipefail
readonly PROGRAM_NAME="nix-cache-upload"
readonly MAX_SINGLE_PUT_BYTES=$((5 * 1024 * 1024 * 1024))
readonly DEFAULT_RETRIES=3
cache_url=""
package_name=""
version_name=""
token_file=""
retry_count="$DEFAULT_RETRIES"
retention_days=""
tag_pairs=()
installables=()
temporary_directory=""
file_cache=""
curl_config=""
success=false
usage() {
cat <<'EOF'
Usage:
nix-cache-upload --to https://cache.example.org --package NAME --version NAME [options] INSTALLABLE...
Publish the complete closure of one or more Nix installables. NARs are uploaded
directly to R2 through presigned URLs; narinfo metadata is published only after
every referenced NAR has completed and is indexed.
Required:
--to URL HTTPS cache origin without a path
--package NAME Package name for version registration
--version NAME Opaque version name for version registration
Options:
--token-file PATH Read the write token from PATH (overrides NIX_CACHE_WRITE_TOKEN)
--tag KEY=VALUE Add a version tag; may be specified up to 64 times
--retention-days DAYS Set the version retention override (0 through 36500)
--retries COUNT Retries after the first request attempt (default: 3)
--help Show this help text
The write token is read from NIX_CACHE_WRITE_TOKEN when --token-file is absent.
Use -- before an installable when it could otherwise look like an option.
EOF
}
die() {
printf '%s: %s\n' "$PROGRAM_NAME" "$*" >&2
exit 1
}
cleanup() {
local status="$?"
if [[ -n "$temporary_directory" && -d "$temporary_directory" ]]; then
if [[ "$status" -eq 0 && "$success" == true ]]; then
rm -rf -- "$temporary_directory"
else
printf '%s: upload did not finish; temporary cache retained at %s\n' "$PROGRAM_NAME" "$temporary_directory" >&2
fi
fi
exit "$status"
}
trap cleanup EXIT
require_command() {
command -v "$1" >/dev/null 2>&1 || die "required command not found: $1"
}
valid_name() {
[[ "$1" =~ ^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$ ]]
}
valid_tag() {
local pair="$1"
local key="${pair%%=*}"
local value="${pair#*=}"
[[ "$pair" == *=* ]] && [[ "$key" =~ ^[A-Za-z0-9._~-]{1,64}$ ]] && [[ ${#value} -le 256 ]]
}
retryable_status() {
local status="$1"
[[ "$status" == "000" || "$status" == "408" || "$status" == "429" || "$status" =~ ^5[0-9][0-9]$ ]]
}
retry_delay() {
local attempt="$1"
local seconds=$((1 << attempt))
if [[ "$seconds" -gt 8 ]]; then seconds=8; fi
sleep "$seconds"
}
curl_escape() {
local value="$1"
[[ "$value" != *$'\n'* && "$value" != *$'\r'* ]] || die "unsafe value returned for curl configuration"
value="${value//\\/\\\\}"
value="${value//\"/\\\"}"
printf '%s' "$value"
}
curl_config_line() {
local config_file="$1"
local key="$2"
local value="$3"
printf '%s = "%s"\n' "$key" "$(curl_escape "$value")" >> "$config_file"
}
curl_status() {
local response_file="$1"
shift
local status
status="$(curl "$@" --output "$response_file" --write-out '%{http_code}' 2>/dev/null)" || status="000"
if [[ ! "$status" =~ ^[0-9]{3}$ ]]; then status="000"; fi
printf '%s' "$status"
}
api_request() {
local method="$1"
local url="$2"
local response_file="$3"
local payload_file="${4:-}"
local -a arguments=(--config "$curl_config" --request "$method")
if [[ -n "$payload_file" ]]; then
arguments+=(--header "Content-Type: application/json" --data-binary "@$payload_file")
fi
curl_status "$response_file" "${arguments[@]}" "$url"
}
write_direct_curl_config() {
local config_file="$1"
local upload_url="$2"
local content_type="$3"
local if_none_match="$4"
local cache_control="$5"
local checksum_sha256="$6"
local nar_file="$7"
[[ "$upload_url" =~ ^https://[[:xdigit:]]{32}\.r2\.cloudflarestorage\.com/.*/_nix_uploads/ ]] || die "direct upload returned an unexpected R2 staging URL"
[[ "$content_type" == "application/octet-stream" ]] || die "direct upload returned an unexpected Content-Type"
[[ "$if_none_match" == "*" ]] || die "direct upload returned an unexpected If-None-Match value"
[[ "$cache_control" == "public, max-age=31536000, immutable" ]] || die "direct upload returned an unexpected Cache-Control value"
[[ -n "$checksum_sha256" ]] || die "direct upload returned an unexpected SHA-256 checksum"
: > "$config_file"
chmod 600 "$config_file"
printf '%s\n' 'silent' >> "$config_file"
curl_config_line "$config_file" 'url' "$upload_url"
curl_config_line "$config_file" 'request' 'PUT'
curl_config_line "$config_file" 'header' "Content-Type: $content_type"
curl_config_line "$config_file" 'header' "If-None-Match: $if_none_match"
curl_config_line "$config_file" 'header' "Cache-Control: $cache_control"
curl_config_line "$config_file" 'header' "x-amz-checksum-sha256: $checksum_sha256"
curl_config_line "$config_file" 'upload-file' "$nar_file"
}
initialize_upload() {
local nar_key="$1"
local nar_size="$2"
local nar_sha256="$3"
local response_file="$temporary_directory/upload-spec.json"
local request_file="$temporary_directory/upload-request.json"
local attempt status
jq --null-input --compact-output \
--arg key "$nar_key" \
--arg sha256 "$nar_sha256" \
--argjson size "$nar_size" \
'{key: $key, size: $size, sha256: $sha256}' > "$request_file"
for ((attempt = 0; attempt <= retry_count; attempt++)); do
status="$(api_request POST "$cache_url/api/uploads" "$response_file" "$request_file")"
if [[ "$status" == "200" || "$status" == "201" ]]; then
cat "$response_file"
return 0
fi
if retryable_status "$status" && [[ "$attempt" -lt "$retry_count" ]]; then
retry_delay "$attempt"
continue
fi
die "could not create a direct upload URL for $nar_key (HTTP $status)"
done
}
complete_upload() {
local upload_id="$1"
local nar_key="$2"
local response_file="$temporary_directory/upload-complete.json"
local attempt status error_summary
for ((attempt = 0; attempt <= retry_count; attempt++)); do
status="$(api_request POST "$cache_url/api/uploads/$upload_id/complete" "$response_file")"
if [[ "$status" == "200" || "$status" == "201" ]]; then
return 0
fi
if [[ "$attempt" -lt "$retry_count" ]]; then
if retryable_status "$status" || {
[[ "$status" == "409" || "$status" == "424" ]] && jq --exit-status --raw-output \
'(.error.code // "") == "upload_not_found" or (.error.code // "") == "upload_in_progress" or (.error.code // "") == "upload_not_ready"' \
"$response_file" >/dev/null 2>&1
}; then
retry_delay "$attempt"
continue
fi
fi
error_summary="$(jq --raw-output '
if type == "object" and (.error | type) == "object" then
[(.error.code // empty), (.error.message // empty), (.error.details.errorCode // empty), (.error.details.claimExpiresAt // empty)]
| map(select(type == "string" and length > 0))
| unique
| join(": ")
else
""
end
' "$response_file" 2>/dev/null || true)"
if [[ -n "$error_summary" ]]; then
die "could not complete direct upload $nar_key (HTTP $status; $error_summary)"
fi
die "could not complete direct upload $nar_key (HTTP $status)"
done
}
upload_nar() {
local nar_key="$1"
local nar_file="$2"
local nar_size nar_sha256 session already_exists upload_id upload_url content_type if_none_match cache_control checksum_sha256
local direct_config response_file attempt status
nar_size="$(wc -c < "$nar_file" | tr -d '[:space:]')"
[[ "$nar_size" =~ ^[0-9]+$ ]] || die "could not determine size for $nar_key"
[[ "$nar_size" -le "$MAX_SINGLE_PUT_BYTES" ]] || die "$nar_key exceeds the 5 GiB single-PUT R2 limit; resumable uploads are not supported"
nar_sha256="$(nix hash file --type sha256 --base16 "$nar_file")"
[[ "$nar_sha256" =~ ^[0-9a-f]{64}$ ]] || die "could not calculate a SHA-256 digest for $nar_key"
printf 'Preparing direct upload for %s (%s bytes)\n' "$nar_key" "$nar_size"
session="$(initialize_upload "$nar_key" "$nar_size" "$nar_sha256")"
already_exists="$(jq --raw-output 'if .alreadyExists == true then "true" else "false" end' <<< "$session")" || die "direct upload response was not valid JSON"
if [[ "$already_exists" == "true" ]]; then
printf 'NAR already exists: %s\n' "$nar_key"
return 0
fi
upload_id="$(jq --exit-status --raw-output '.uploadId // empty' <<< "$session")" || die "direct upload response did not contain uploadId"
upload_url="$(jq --exit-status --raw-output '.uploadUrl // empty' <<< "$session")" || die "direct upload response did not contain uploadUrl"
content_type="$(jq --exit-status --raw-output '.uploadHeaders["Content-Type"] // empty' <<< "$session")" || die "direct upload response did not contain Content-Type"
if_none_match="$(jq --exit-status --raw-output '.uploadHeaders["If-None-Match"] // empty' <<< "$session")" || die "direct upload response did not contain If-None-Match"
cache_control="$(jq --exit-status --raw-output '.uploadHeaders["Cache-Control"] // empty' <<< "$session")" || die "direct upload response did not contain Cache-Control"
checksum_sha256="$(jq --exit-status --raw-output '.uploadHeaders["x-amz-checksum-sha256"] // empty' <<< "$session")" || die "direct upload response did not contain SHA-256 checksum"
[[ -n "$upload_url" && -n "$content_type" && -n "$if_none_match" && -n "$cache_control" && -n "$checksum_sha256" ]] || die "direct upload response was incomplete"
direct_config="$temporary_directory/direct-$nar_size-$nar_sha256.curl"
write_direct_curl_config "$direct_config" "$upload_url" "$content_type" "$if_none_match" "$cache_control" "$checksum_sha256" "$nar_file"
response_file="$temporary_directory/direct-response"
for ((attempt = 0; attempt <= retry_count; attempt++)); do
status="$(curl_status "$response_file" --config "$direct_config")"
if [[ "$status" =~ ^2[0-9][0-9]$ || "$status" == "412" ]]; then
complete_upload "$upload_id" "$nar_key"
printf 'NAR completed: %s\n' "$nar_key"
return 0
fi
if retryable_status "$status" && [[ "$attempt" -lt "$retry_count" ]]; then
retry_delay "$attempt"
continue
fi
die "direct R2 upload failed for $nar_key (HTTP $status)"
done
}
publish_narinfo() {
local narinfo_key="$1"
local narinfo_file="$2"
local response_file="$temporary_directory/narinfo-response"
local attempt status error_summary
printf 'Publishing narinfo: %s\n' "$narinfo_key"
for ((attempt = 0; attempt <= retry_count; attempt++)); do
status="$(curl_status "$response_file" --config "$curl_config" --request PUT --upload-file "$narinfo_file" "$cache_url/$narinfo_key")"
if [[ "$status" == "201" || "$status" == "204" ]]; then
return 0
fi
if retryable_status "$status" && [[ "$attempt" -lt "$retry_count" ]]; then
retry_delay "$attempt"
continue
fi
error_summary="$(jq --raw-output '
if type == "object" and (.error | type) == "object" then
[(.error.code // empty), (.error.message // empty), (.error.details.narKey // empty)]
| map(select(type == "string" and length > 0))
| unique
| join(": ")
else
""
end
' "$response_file" 2>/dev/null || true)"
if [[ -n "$error_summary" ]]; then
die "could not publish narinfo $narinfo_key (HTTP $status; $error_summary)"
fi
die "could not publish narinfo $narinfo_key (HTTP $status)"
done
}
register_version() {
local narinfo_keys_file="$1"
local tags_file="$temporary_directory/tags.json"
local body_file="$temporary_directory/register-version.json"
local response_file="$temporary_directory/register-version-response.json"
local retention_json='null'
local pair key value attempt status
printf '{}' > "$tags_file"
for pair in "${tag_pairs[@]}"; do
key="${pair%%=*}"
value="${pair#*=}"
jq --arg key "$key" --arg value "$value" '.[$key] = $value' "$tags_file" > "$tags_file.next"
mv "$tags_file.next" "$tags_file"
done
if [[ -n "$retention_days" ]]; then retention_json="$retention_days"; fi
jq --null-input \
--rawfile narinfo_keys "$narinfo_keys_file" \
--slurpfile tags "$tags_file" \
--argjson retention_days "$retention_json" \
'{narinfoKeys: ($narinfo_keys | split("\n") | map(select(length > 0))), tags: $tags[0]}
+ (if $retention_days == null then {} else {retentionDays: $retention_days} end)' > "$body_file"
printf 'Registering %s/%s\n' "$package_name" "$version_name"
for ((attempt = 0; attempt <= retry_count; attempt++)); do
status="$(api_request PUT "$cache_url/api/packages/$package_name/versions/$version_name" "$response_file" "$body_file")"
if [[ "$status" == "200" || "$status" == "201" ]]; then
return 0
fi
if retryable_status "$status" && [[ "$attempt" -lt "$retry_count" ]]; then
retry_delay "$attempt"
continue
fi
die "could not register $package_name/$version_name (HTTP $status)"
done
}
while [[ "$#" -gt 0 ]]; do
case "$1" in
--to) [[ "$#" -ge 2 ]] || die "--to requires a value"; cache_url="${2%/}"; shift 2 ;;
--package) [[ "$#" -ge 2 ]] || die "--package requires a value"; package_name="$2"; shift 2 ;;
--version) [[ "$#" -ge 2 ]] || die "--version requires a value"; version_name="$2"; shift 2 ;;
--token-file) [[ "$#" -ge 2 ]] || die "--token-file requires a value"; token_file="$2"; shift 2 ;;
--tag) [[ "$#" -ge 2 ]] || die "--tag requires KEY=VALUE"; tag_pairs+=("$2"); shift 2 ;;
--retention-days) [[ "$#" -ge 2 ]] || die "--retention-days requires a value"; retention_days="$2"; shift 2 ;;
--retries) [[ "$#" -ge 2 ]] || die "--retries requires a value"; retry_count="$2"; shift 2 ;;
--help) usage; success=true; exit 0 ;;
--) shift; installables=("$@"); break ;;
-*) die "unknown option: $1" ;;
*) installables=("$@"); break ;;
esac
done
[[ "$cache_url" =~ ^https://[^/]+$ ]] || die "--to must be an HTTPS origin without a path"
valid_name "$package_name" || die "--package must be a URL-safe single path segment"
valid_name "$version_name" || die "--version must be a URL-safe single path segment"
[[ ${#installables[@]} -gt 0 ]] || die "at least one installable is required"
[[ "$retry_count" =~ ^[0-9]+$ && "$retry_count" -le 20 ]] || die "--retries must be an integer from 0 through 20"
[[ -z "$retention_days" || "$retention_days" =~ ^[0-9]+$ && "$retention_days" -le 36500 ]] || die "--retention-days must be an integer from 0 through 36500"
[[ ${#tag_pairs[@]} -le 64 ]] || die "at most 64 --tag options are supported"
for pair in "${tag_pairs[@]}"; do valid_tag "$pair" || die "invalid tag: $pair"; done
for command_name in nix curl jq find awk wc sort mktemp chmod tr; do require_command "$command_name"; done
if [[ -n "$token_file" ]]; then
[[ -f "$token_file" && -r "$token_file" ]] || die "--token-file is not a readable regular file"
write_token="$(<"$token_file")"
else
write_token="${NIX_CACHE_WRITE_TOKEN:-}"
fi
[[ -n "$write_token" && "$write_token" != *$'\n'* && "$write_token" != *$'\r'* ]] || die "a single-line write token is required via --token-file or NIX_CACHE_WRITE_TOKEN"
temporary_directory="$(mktemp -d "${TMPDIR:-/tmp}/nix-cache-upload.XXXXXXXX")"
chmod 700 "$temporary_directory"
file_cache="$temporary_directory/file-cache"
mkdir -p "$file_cache"
curl_config="$temporary_directory/api.curl"
: > "$curl_config"
chmod 600 "$curl_config"
printf '%s\n' 'silent' >> "$curl_config"
curl_config_line "$curl_config" 'header' "Authorization: Bearer $write_token"
printf 'Generating a Nix file cache for %s installable(s)\n' "${#installables[@]}"
nix copy --to "file://$file_cache" "${installables[@]}"
narinfo_records="$temporary_directory/narinfo-records"
nar_records="$temporary_directory/nar-records"
: > "$narinfo_records"
: > "$nar_records"
narinfo_count=0
while IFS= read -r narinfo_file; do
narinfo_key="$(basename "$narinfo_file")"
nar_key="$(awk '$1 == "URL:" { print substr($0, 6); exit }' "$narinfo_file")"
[[ "$narinfo_key" =~ ^[A-Za-z0-9._~-]+\.narinfo$ ]] || die "generated an invalid narinfo key: $narinfo_key"
[[ "$nar_key" =~ ^nar/[A-Za-z0-9._~/-]+$ && "$nar_key" != *..* ]] || die "narinfo $narinfo_key references an unsupported NAR key"
nar_file="$file_cache/$nar_key"
[[ -f "$nar_file" ]] || die "narinfo $narinfo_key references a missing NAR"
printf '%s\t%s\n' "$narinfo_key" "$narinfo_file" >> "$narinfo_records"
printf '%s\t%s\n' "$nar_key" "$nar_file" >> "$nar_records"
narinfo_count=$((narinfo_count + 1))
done < <(find "$file_cache" -maxdepth 1 -type f -name '*.narinfo' -print | LC_ALL=C sort)
[[ "$narinfo_count" -gt 0 ]] || die "Nix did not generate any narinfo files"
LC_ALL=C sort -u "$nar_records" > "$nar_records.sorted"
while IFS=$'\t' read -r nar_key nar_file; do
upload_nar "$nar_key" "$nar_file"
done < "$nar_records.sorted"
LC_ALL=C sort -u "$narinfo_records" > "$narinfo_records.sorted"
narinfo_keys="$temporary_directory/narinfo-keys"
: > "$narinfo_keys"
while IFS=$'\t' read -r narinfo_key narinfo_file; do
publish_narinfo "$narinfo_key" "$narinfo_file"
printf '%s\n' "$narinfo_key" >> "$narinfo_keys"
done < "$narinfo_records.sorted"
register_version "$narinfo_keys"
printf 'Published and registered %s Nix cache path(s) as %s/%s\n' "$narinfo_count" "$package_name" "$version_name"
success=true