180 lines
5.9 KiB
Python
180 lines
5.9 KiB
Python
# /// script
|
|
# dependencies = [
|
|
# "requests",
|
|
# ]
|
|
# ///
|
|
# For local development without R2 credentials, use download-small-fixtures-http.py instead.
|
|
|
|
import hashlib
|
|
import os
|
|
import subprocess
|
|
import time
|
|
|
|
import requests
|
|
from download_fixtures_consts import (
|
|
PART_SIZE,
|
|
R2_PUBLIC_BUCKET_URL,
|
|
R2_S3_ENDPOINT_URL,
|
|
)
|
|
from download_fixtures_consts import (
|
|
SMALL_FIXTURES as FIXTURES,
|
|
)
|
|
from download_fixtures_consts import (
|
|
SMALL_FIXTURES_DIR as FIXTURES_DIR,
|
|
)
|
|
|
|
# cd to directory of this file
|
|
os.chdir(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
# =============================================================================
|
|
# Shared utilities
|
|
# =============================================================================
|
|
|
|
|
|
def calculate_etag(file_path):
|
|
"""Calculate S3/R2 style ETag for a file."""
|
|
file_size = os.path.getsize(file_path)
|
|
num_parts = (file_size + PART_SIZE - 1) // PART_SIZE
|
|
|
|
if num_parts == 1:
|
|
# Single part upload - just MD5 of the file
|
|
with open(file_path, "rb") as f:
|
|
return hashlib.md5(f.read()).hexdigest()
|
|
else:
|
|
# Multipart upload - concatenate MD5s of each part
|
|
md5s = []
|
|
with open(file_path, "rb") as f:
|
|
while True:
|
|
chunk = f.read(PART_SIZE)
|
|
if not chunk:
|
|
break
|
|
md5s.append(hashlib.md5(chunk).digest())
|
|
|
|
# Calculate MD5 of concatenated part MD5s
|
|
combined_md5 = hashlib.md5(b"".join(md5s)).hexdigest()
|
|
return f"{combined_md5}-{num_parts}"
|
|
|
|
|
|
def get_remote_etag(remote_filename, retries=3):
|
|
"""Get ETag from R2 bucket via public URL."""
|
|
for i in range(retries):
|
|
try:
|
|
response = requests.head(f"{R2_PUBLIC_BUCKET_URL}/{remote_filename}", timeout=30)
|
|
response.raise_for_status()
|
|
return response.headers.get("ETag", "").strip('"')
|
|
except Exception as e:
|
|
if i < retries - 1:
|
|
print(
|
|
f"Error getting ETag for `{remote_filename}` (attempt {i + 1} of {retries}): {e}",
|
|
flush=True,
|
|
)
|
|
time.sleep(1)
|
|
else:
|
|
raise
|
|
|
|
|
|
def verify_etags():
|
|
"""Verify ETags of all downloaded fixtures match remote."""
|
|
mismatches = []
|
|
for remote_filename in FIXTURES.keys():
|
|
local_file = FIXTURES_DIR / remote_filename
|
|
if not local_file.exists():
|
|
raise Exception(f"Fixture {remote_filename} not found after sync")
|
|
|
|
local_etag = calculate_etag(local_file)
|
|
remote_etag = get_remote_etag(remote_filename)
|
|
|
|
if local_etag != remote_etag:
|
|
mismatches.append(f"{remote_filename}: local={local_etag}, remote={remote_etag}")
|
|
else:
|
|
print(f"ETag OK: {remote_filename}", flush=True)
|
|
|
|
if mismatches:
|
|
raise Exception("ETag mismatches after sync:\n" + "\n".join(mismatches))
|
|
|
|
|
|
def rename_fixtures():
|
|
"""Rename downloaded fixtures from remote names to local names."""
|
|
for remote_filename, local_filename in FIXTURES.items():
|
|
if remote_filename != local_filename:
|
|
src = FIXTURES_DIR / remote_filename
|
|
dst = FIXTURES_DIR / local_filename
|
|
if src.exists():
|
|
src.rename(dst)
|
|
print(f"Renamed {remote_filename} -> {local_filename}", flush=True)
|
|
|
|
|
|
# =============================================================================
|
|
# Authenticated path: s5cmd download (used in CI with R2 credentials)
|
|
# =============================================================================
|
|
|
|
|
|
def download_fixtures_from_r2(retries: int = 3) -> None:
|
|
"""Download fixtures from R2 using s5cmd with retry logic."""
|
|
batch_commands = "\n".join(f"sync s3://tensorzero-fixtures/{f} {FIXTURES_DIR}/" for f in FIXTURES.keys())
|
|
|
|
cmd = [
|
|
"s5cmd",
|
|
"--endpoint-url",
|
|
R2_S3_ENDPOINT_URL,
|
|
"run",
|
|
]
|
|
|
|
env = {
|
|
"PATH": os.environ.get("PATH", ""),
|
|
"AWS_ACCESS_KEY_ID": os.environ["R2_ACCESS_KEY_ID"],
|
|
"AWS_SECRET_ACCESS_KEY": os.environ["R2_SECRET_ACCESS_KEY"],
|
|
}
|
|
|
|
for attempt in range(retries):
|
|
print(f"Running s5cmd (attempt {attempt + 1} of {retries})...", flush=True)
|
|
result = subprocess.run(cmd, input=batch_commands, text=True, env=env)
|
|
|
|
if result.returncode == 0:
|
|
print("Download completed successfully. Verifying ETags...", flush=True)
|
|
try:
|
|
verify_etags()
|
|
rename_fixtures()
|
|
return
|
|
except Exception as e:
|
|
print(
|
|
f"Verification failed (attempt {attempt + 1} of {retries}): {e}",
|
|
flush=True,
|
|
)
|
|
if attempt >= retries - 1:
|
|
raise
|
|
else:
|
|
print(
|
|
f"s5cmd failed with exit code {result.returncode} (attempt {attempt + 1} of {retries})",
|
|
flush=True,
|
|
)
|
|
|
|
if attempt < retries - 1:
|
|
sleep_time = 3**attempt # Exponential backoff: 1, 3, 9 seconds
|
|
print(f"Retrying in {sleep_time} seconds...", flush=True)
|
|
time.sleep(sleep_time)
|
|
|
|
raise Exception(f"s5cmd download failed after {retries} attempts")
|
|
|
|
|
|
# =============================================================================
|
|
# Main
|
|
# =============================================================================
|
|
|
|
|
|
def main():
|
|
FIXTURES_DIR.mkdir(exist_ok=True)
|
|
|
|
if not os.environ.get("R2_ACCESS_KEY_ID") or not os.environ.get("R2_SECRET_ACCESS_KEY"):
|
|
raise Exception(
|
|
"R2_ACCESS_KEY_ID and R2_SECRET_ACCESS_KEY must be set. "
|
|
"For local development without R2 credentials, use download-small-fixtures-http.py instead."
|
|
)
|
|
|
|
print("R2 credentials found, downloading fixtures using `s5cmd`", flush=True)
|
|
download_fixtures_from_r2()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|