Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / maps / upload_planet.py

upload_planet.py933 lines · 40.8 KiBRaw
1"""Upload any local file to R2 as planet3.mamaps (bucket: maps).
2
3Usage: python upload_planet.py <local-file> [--key K] [options]
4 python upload_planet.py --manifest <overlay-dir> --overlay-seq N --base-build-id HEX [--key K]
5 [--manifest-key M] [options]
6 python upload_planet.py --rebase --overlay-seq N --base-build-id HEX --base-len N [--key K]
7 [--manifest-key M] [--base-sha256 HEX] [--dry-run]
8
9--key names the base object (default planet3.mamaps). The manifest written by
10--manifest / --rebase goes to --manifest-key, which defaults to the name
11derived from --key (planetN.mamaps -> planetN.manifest.json; any other key ->
12planet3.manifest.json), so `--key planet4.mamaps` publishes a planet4 stack
13without touching planet3.* (which the shipped apps read). Without --key every
14mode behaves exactly as before.
15
16Serves https://data.maproj.org/planet3.mamaps, which the apps'
17basemap URLs point at (library/map urls.rs, maps MapTileCache.kt).
18
19The base upload is a resumable multipart upload with end-to-end hash checks:
20
21* Parts are uploaded concurrently (--part-size-mb / --concurrency, or the
22 R2_PART_SIZE_MB / R2_CONCURRENCY env vars). The default part size is
23 64 MiB, raised automatically so the upload never needs more than 9,000
24 parts (R2 allows 10,000, all but the last the same size, 5 MiB..5 GiB):
25 a ~80 GB planet is ~1,200 parts. Each part carries Content-MD5, so R2
26 rejects a part that was corrupted in flight, and its returned ETag is
27 checked against the local MD5.
28* The upload id and every completed part (number + ETag) are persisted in a
29 state file (default <local-file>.upload-state.json) after each part. A rerun
30 after a crash or a dropped link lists the parts R2 already holds, keeps every
31 one whose ETag matches the local bytes, and uploads only the rest. The state
32 is discarded (and the stale upload aborted) if the file, key or part size
33 changed; --no-resume forces a fresh upload.
34* The SHA-256 of the whole file is computed while the parts upload (one
35 sequential reader beside the part workers) and compared with the
36 `sha256sum`-format sidecar <local-file>.sha256 that `mamaps_pack
37 --sha256-out` writes, when it is present (or --sha256 HEX). A mismatch means
38 the local copy is not the file the build produced (e.g. a bad pull from the
39 build box): the upload is aborted before CompleteMultipartUpload, so nothing
40 becomes visible. The hash is stored as object metadata (x-amz-meta-sha256)
41 and checked after completion with a HEAD, together with the size.
42* --dry-run exercises all of the above -- reading, MD5/SHA-256, part planning,
43 state file, resume -- against an in-process fake bucket persisted next to the
44 state file, and makes no network calls at all.
45
46The --manifest form publishes a patch-overlay update: it uploads each
47overlay-*.mamaps segment from the overlay dir under overlays/<seq>/,
48then writes planet3.manifest.json (base pin + segment list + hashes).
49The manifest is the only file the client fetches on a check. Segments that
50R2 already holds with the same size and x-amz-meta-sha256 are not re-uploaded;
51every segment is HEAD-verified (size + server hash vs local hash) before the
52manifest is written, and the base the manifest pins is HEAD-checked too
53(its size against --base-len, and its stored hash against --base-sha256 when
54given).
55
56SECURITY: credentials/config come from ENVIRONMENT VARIABLES, never baked
57into this file (the analysis/ original carried hardcoded keys and must
58stay gitignored there). Never paste keys on the command line — `export`
59them instead, ideally from a secret store.
60
61Required env (not for --dry-run):
62 R2_ENDPOINT S3 API endpoint, e.g. https://<ACCOUNT_ID>.r2.cloudflarestorage.com
63 R2_ACCESS_KEY_ID R2 access key id
64 R2_SECRET_ACCESS_KEY R2 secret access key
65Optional env:
66 R2_BUCKET Default: maps
67 R2_CDN Default: https://data.maproj.org (URL prefix written into the manifest)
68 R2_PART_SIZE_MB Default: 64 (raised to keep the part count <= 9,000)
69 R2_CONCURRENCY Default: 16 parts in flight (each holds one part in memory)
70"""
71import argparse
72import base64
73import hashlib
74import json
75import os
76import random
77import sys
78import threading
79import time
80import uuid
81from concurrent.futures import ThreadPoolExecutor, as_completed
82
83BUCKET = os.environ.get("R2_BUCKET", "maps")
84KEY = "planet3.mamaps"
85MANIFEST_KEY = "planet3.manifest.json"
86
87
88def manifest_key_for(key: str) -> str:
89 """planetN.mamaps -> planetN.manifest.json; anything else -> MANIFEST_KEY."""
90 if key.endswith(".mamaps") and "/" not in key:
91 return key[: -len(".mamaps")] + ".manifest.json"
92 return MANIFEST_KEY
93
94
95def add_key_args(ap: argparse.ArgumentParser) -> None:
96 ap.add_argument("--key", default=KEY, help=f"base object key (default {KEY})")
97 ap.add_argument("--manifest-key", default=None,
98 help="manifest object key (default derived from --key: planetN.mamaps -> "
99 f"planetN.manifest.json; {MANIFEST_KEY} for the default key)")
100
101
102def manifest_key(args) -> str:
103 return args.manifest_key or manifest_key_for(args.key)
104CDN = os.environ.get("R2_CDN", "https://data.maproj.org")
105
106MIB = 1024 * 1024
107DEFAULT_PART_MB = 64
108DEFAULT_CONCURRENCY = 16
109MIN_PART = 5 * MIB # S3/R2 floor for every part but the last
110MAX_PART = 5 * 1024 * MIB # S3/R2 ceiling
111MAX_PARTS = 10_000 # S3/R2 hard limit
112TARGET_MAX_PARTS = 9_000 # what auto-sizing aims under, leaving slack
113PART_ATTEMPTS = 5 # per-part attempts on top of botocore's own retries
114RETRY_BASE_S = 2.0 # first backoff between part attempts (doubles, capped at 60 s)
115HASH_CHUNK = 8 * MIB
116META_SHA = "sha256" # stored as x-amz-meta-sha256
117
118MANIFEST_VERSION = 1
119MIN_CLIENT_COMPAT = 1
120
121
122def log(msg: str) -> None:
123 print(msg, flush=True)
124
125
126# --------------------------------------------------------------------------
127# Configuration
128# --------------------------------------------------------------------------
129
130def env_int(name: str, default: int) -> int:
131 raw = os.environ.get(name)
132 if raw is None or raw.strip() == "":
133 return default
134 try:
135 v = int(raw)
136 except ValueError:
137 raise SystemExit(f"{name}={raw!r} is not an integer")
138 if v <= 0:
139 raise SystemExit(f"{name} must be positive, not {v}")
140 return v
141
142
143def plan_part_size(size: int, requested_mb: int) -> int:
144 """Part size in bytes: the request, raised so `size` needs <= TARGET_MAX_PARTS
145 parts, rounded up to a whole MiB and clamped to the S3/R2 limits."""
146 part = max(requested_mb * MIB, MIN_PART)
147 need = -(-size // TARGET_MAX_PARTS) # ceil
148 if part < need:
149 part = -(-need // MIB) * MIB
150 if part > MAX_PART:
151 raise SystemExit(f"{size} bytes would need parts over 5 GiB; too large for one object")
152 if -(-size // part) > MAX_PARTS:
153 raise SystemExit(f"{size} bytes in {part}-byte parts is over {MAX_PARTS} parts")
154 return part
155
156
157def add_transfer_args(ap: argparse.ArgumentParser) -> None:
158 ap.add_argument("--part-size-mb", type=int, default=None,
159 help=f"multipart part size in MiB (env R2_PART_SIZE_MB, default {DEFAULT_PART_MB}; "
160 f"raised automatically to stay under {TARGET_MAX_PARTS} parts)")
161 ap.add_argument("--concurrency", type=int, default=None,
162 help=f"parts in flight (env R2_CONCURRENCY, default {DEFAULT_CONCURRENCY})")
163 ap.add_argument("--dry-run", action="store_true",
164 help="do everything except network calls, against a local fake bucket")
165
166
167def transfer_settings(args) -> tuple:
168 part_mb = args.part_size_mb if args.part_size_mb is not None else env_int("R2_PART_SIZE_MB", DEFAULT_PART_MB)
169 conc = args.concurrency if args.concurrency is not None else env_int("R2_CONCURRENCY", DEFAULT_CONCURRENCY)
170 if part_mb <= 0 or conc <= 0:
171 raise SystemExit("--part-size-mb and --concurrency must be positive")
172 return part_mb, conc
173
174
175# --------------------------------------------------------------------------
176# Clients
177# --------------------------------------------------------------------------
178
179def make_client(concurrency: int):
180 """A real boto3 client for R2. boto3 is imported here so --dry-run and the
181 unit tests run without it."""
182 missing = [v for v in ("R2_ENDPOINT", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY")
183 if not os.environ.get(v)]
184 if missing:
185 raise SystemExit(f"missing env: {', '.join(missing)} (see module docstring)")
186 import boto3
187 from botocore.config import Config
188 cfg = dict(
189 # One pooled connection per part in flight, plus a few for HEAD/list.
190 max_pool_connections=concurrency + 4,
191 retries={"max_attempts": 10, "mode": "adaptive"},
192 connect_timeout=30,
193 read_timeout=300,
194 )
195 # botocore >= 1.36 adds CRC checksums to every upload by default; R2 does
196 # not accept all of them. Content-MD5 (set per part below) is the integrity
197 # check here, so only compute checksums where an operation requires them.
198 try:
199 client_cfg = Config(request_checksum_calculation="when_required",
200 response_checksum_validation="when_required", **cfg)
201 except TypeError:
202 client_cfg = Config(**cfg)
203 return boto3.client(
204 "s3",
205 endpoint_url=os.environ["R2_ENDPOINT"],
206 aws_access_key_id=os.environ["R2_ACCESS_KEY_ID"],
207 aws_secret_access_key=os.environ["R2_SECRET_ACCESS_KEY"],
208 region_name="auto",
209 config=client_cfg,
210 )
211
212
213class ClientError(Exception):
214 """Raised by FakeS3 with the same `.response["Error"]["Code"]` shape botocore uses."""
215
216 def __init__(self, code: str, msg: str = ""):
217 super().__init__(f"{code}: {msg}")
218 self.response = {"Error": {"Code": code, "Message": msg}}
219
220
221def error_code(e: Exception) -> str:
222 return getattr(e, "response", {}).get("Error", {}).get("Code", "")
223
224
225class FakeS3:
226 """The subset of the S3 API this script uses, in memory, optionally persisted
227 to a JSON file so a dry run can be interrupted and resumed like the real
228 thing. Object bodies are never stored -- only sizes, MD5s and metadata --
229 so a dry run of an 80 GB file costs kilobytes. It validates what R2 would:
230 Content-MD5 against the body, part sizes, part order and ETags on complete.
231
232 `fail_after_parts` (tests / UPLOAD_PLANET_FAIL_AFTER_PARTS) raises on the
233 Nth successful UploadPart to simulate a dropped link."""
234
235 def __init__(self, persist_path: str = None, fail_after_parts: int = None):
236 self.path = persist_path
237 self.lock = threading.Lock()
238 self.uploads = {} # upload_id -> {"bucket","key","meta","parts":{n: [size, etag]}}
239 self.objects = {} # "bucket/key" -> {"size", "meta", "etag"}
240 self.calls = [] # (op, detail) log, for tests
241 self.fail_after = fail_after_parts
242 self.part_ok = 0
243 if self.path and os.path.exists(self.path):
244 with open(self.path) as f:
245 st = json.load(f)
246 self.uploads = {k: {**v, "parts": {int(n): p for n, p in v["parts"].items()}}
247 for k, v in st.get("uploads", {}).items()}
248 self.objects = st.get("objects", {})
249
250 def _save(self):
251 if not self.path:
252 return
253 tmp = self.path + ".tmp"
254 with open(tmp, "w") as f:
255 json.dump({"uploads": self.uploads, "objects": self.objects}, f)
256 os.replace(tmp, self.path)
257
258 def create_multipart_upload(self, Bucket, Key, Metadata=None, **_):
259 with self.lock:
260 uid = "dryrun-" + uuid.uuid4().hex
261 self.uploads[uid] = {"bucket": Bucket, "key": Key, "meta": dict(Metadata or {}), "parts": {}}
262 self.calls.append(("create", Key))
263 self._save()
264 return {"UploadId": uid}
265
266 def upload_part(self, Bucket, Key, UploadId, PartNumber, Body, ContentMD5=None, **_):
267 body = bytes(Body)
268 md5 = hashlib.md5(body)
269 if ContentMD5 is not None and base64.b64encode(md5.digest()).decode() != ContentMD5:
270 raise ClientError("BadDigest", f"part {PartNumber}")
271 with self.lock:
272 if self.fail_after is not None and self.part_ok >= self.fail_after:
273 raise ConnectionError("simulated dropped link")
274 up = self.uploads.get(UploadId)
275 if up is None:
276 raise ClientError("NoSuchUpload", UploadId)
277 etag = f'"{md5.hexdigest()}"'
278 up["parts"][PartNumber] = [len(body), etag]
279 self.part_ok += 1
280 self.calls.append(("part", PartNumber))
281 self._save()
282 return {"ETag": etag}
283
284 def list_parts(self, Bucket, Key, UploadId, PartNumberMarker=0, MaxParts=1000, **_):
285 with self.lock:
286 up = self.uploads.get(UploadId)
287 if up is None:
288 raise ClientError("NoSuchUpload", UploadId)
289 nums = sorted(n for n in up["parts"] if n > PartNumberMarker)
290 page = nums[:MaxParts]
291 self.calls.append(("list", PartNumberMarker))
292 return {
293 "Parts": [{"PartNumber": n, "Size": up["parts"][n][0], "ETag": up["parts"][n][1]} for n in page],
294 "IsTruncated": len(nums) > MaxParts,
295 "NextPartNumberMarker": page[-1] if page else PartNumberMarker,
296 }
297
298 def complete_multipart_upload(self, Bucket, Key, UploadId, MultipartUpload):
299 with self.lock:
300 up = self.uploads.get(UploadId)
301 if up is None:
302 raise ClientError("NoSuchUpload", UploadId)
303 parts = MultipartUpload["Parts"]
304 nums = [p["PartNumber"] for p in parts]
305 if nums != sorted(nums) or nums != list(range(1, len(nums) + 1)):
306 raise ClientError("InvalidPartOrder", str(nums[:5]))
307 sizes = []
308 for p in parts:
309 have = up["parts"].get(p["PartNumber"])
310 if have is None or have[1] != p["ETag"]:
311 raise ClientError("InvalidPart", str(p["PartNumber"]))
312 sizes.append(have[0])
313 if any(s < MIN_PART for s in sizes[:-1]) or len(set(sizes[:-1])) > 1:
314 raise ClientError("EntityTooSmall", "parts must match and be >= 5 MiB")
315 self.objects[f"{Bucket}/{Key}"] = {"size": sum(sizes), "meta": up["meta"],
316 "etag": f'"multipart-{len(parts)}"'}
317 del self.uploads[UploadId]
318 self.calls.append(("complete", Key))
319 self._save()
320 return {"ETag": self.objects[f"{Bucket}/{Key}"]["etag"]}
321
322 def abort_multipart_upload(self, Bucket, Key, UploadId):
323 with self.lock:
324 self.uploads.pop(UploadId, None)
325 self.calls.append(("abort", Key))
326 self._save()
327 return {}
328
329 def put_object(self, Bucket, Key, Body, Metadata=None, ContentMD5=None, **_):
330 body = bytes(Body)
331 md5 = hashlib.md5(body)
332 if ContentMD5 is not None and base64.b64encode(md5.digest()).decode() != ContentMD5:
333 raise ClientError("BadDigest", Key)
334 with self.lock:
335 self.objects[f"{Bucket}/{Key}"] = {"size": len(body), "meta": dict(Metadata or {}),
336 "etag": f'"{md5.hexdigest()}"'}
337 self.calls.append(("put", Key))
338 self._save()
339 return {"ETag": self.objects[f"{Bucket}/{Key}"]["etag"]}
340
341 def head_object(self, Bucket, Key):
342 with self.lock:
343 o = self.objects.get(f"{Bucket}/{Key}")
344 self.calls.append(("head", Key))
345 if o is None:
346 raise ClientError("404", Key)
347 return {"ContentLength": o["size"], "Metadata": dict(o["meta"]), "ETag": o["etag"]}
348
349
350def dry_run_client(state_path: str):
351 fail = os.environ.get("UPLOAD_PLANET_FAIL_AFTER_PARTS")
352 return FakeS3(persist_path=state_path + ".dryrun-bucket.json",
353 fail_after_parts=int(fail) if fail else None)
354
355
356# --------------------------------------------------------------------------
357# Hashes
358# --------------------------------------------------------------------------
359
360def sha256_file(path: str) -> str:
361 h = hashlib.sha256()
362 with open(path, "rb") as f:
363 while True:
364 chunk = f.read(HASH_CHUNK)
365 if not chunk:
366 break
367 h.update(chunk)
368 return h.hexdigest()
369
370
371def read_sidecar(path: str, name: str) -> str:
372 """The hash from a `sha256sum`-format line (`<hex> <name>`), or None if the
373 file is absent. A malformed line or one naming another file is an error."""
374 if not os.path.exists(path):
375 return None
376 with open(path) as f:
377 lines = [l for l in f.read().splitlines() if l.strip()]
378 if len(lines) != 1:
379 raise SystemExit(f"{path}: expected one `sha256sum` line, found {len(lines)}")
380 parts = lines[0].split()
381 digest = parts[0].lower()
382 if len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest):
383 raise SystemExit(f"{path}: {parts[0]!r} is not a SHA-256")
384 if len(parts) > 1 and parts[-1].lstrip("*") != name:
385 raise SystemExit(f"{path} names {parts[-1]!r}, not {name!r}")
386 return digest
387
388
389def server_sha(head: dict) -> str:
390 meta = {k.lower(): v for k, v in (head.get("Metadata") or {}).items()}
391 v = meta.get(META_SHA)
392 return v.lower() if v else None
393
394
395def head_or_none(s3, bucket: str, key: str):
396 try:
397 return s3.head_object(Bucket=bucket, Key=key)
398 except Exception as e:
399 if error_code(e) in ("404", "NoSuchKey", "NotFound"):
400 return None
401 raise
402
403
404# --------------------------------------------------------------------------
405# Resumable multipart upload
406# --------------------------------------------------------------------------
407
408class State:
409 """The resume record: which upload id, which file, and which parts are done.
410 Rewritten atomically after every part, so a crash loses at most the parts in
411 flight (and those are recovered from ListParts on the next run)."""
412
413 def __init__(self, path: str):
414 self.path = path
415 self.lock = threading.Lock()
416 self.data = None
417
418 def load(self):
419 if not os.path.exists(self.path):
420 return None
421 try:
422 with open(self.path) as f:
423 self.data = json.load(f)
424 except (OSError, ValueError) as e:
425 log(f" ignoring unreadable state file {self.path}: {e}")
426 self.data = None
427 return self.data
428
429 def start(self, **fields):
430 self.data = {**fields, "parts": {}}
431 self.save()
432
433 def part_done(self, n: int, etag: str):
434 with self.lock:
435 self.data["parts"][str(n)] = etag
436 self._write()
437
438 def save(self):
439 with self.lock:
440 self._write()
441
442 def _write(self):
443 tmp = self.path + ".tmp"
444 with open(tmp, "w") as f:
445 json.dump(self.data, f)
446 os.replace(tmp, self.path)
447
448 def remove(self):
449 for p in (self.path, self.path + ".tmp"):
450 try:
451 os.remove(p)
452 except FileNotFoundError:
453 pass
454
455
456def pread(fd: int, want: int, off: int) -> bytes:
457 if hasattr(os, "pread"):
458 return os.pread(fd, want, off)
459 # No positional read (Windows): a private handle per call, so threads never
460 # share a file cursor.
461 with open(_fd_paths[fd], "rb") as f:
462 f.seek(off)
463 return f.read(want)
464
465
466_fd_paths = {}
467
468
469def open_ro(path: str) -> int:
470 fd = os.open(path, os.O_RDONLY | getattr(os, "O_BINARY", 0))
471 _fd_paths[fd] = path
472 return fd
473
474
475def read_part(fd: int, n: int, part_size: int, size: int) -> bytes:
476 off = (n - 1) * part_size
477 want = min(part_size, size - off)
478 buf = pread(fd, want, off)
479 if len(buf) != want:
480 raise IOError(f"short read of part {n}: {len(buf)} of {want} bytes")
481 return buf
482
483
484def list_all_parts(s3, bucket: str, key: str, upload_id: str) -> dict:
485 out, marker = {}, 0
486 while True:
487 r = s3.list_parts(Bucket=bucket, Key=key, UploadId=upload_id, PartNumberMarker=marker)
488 for p in r.get("Parts", []):
489 out[int(p["PartNumber"])] = (int(p["Size"]), p["ETag"])
490 if not r.get("IsTruncated"):
491 return out
492 marker = r["NextPartNumberMarker"]
493
494
495def multipart_upload(s3, src: str, bucket: str, key: str, part_mb: int, concurrency: int,
496 state_path: str, expected_sha: str = None, resume: bool = True,
497 verify_local: bool = True) -> int:
498 """Upload `src` to bucket/key; returns a process exit code (0 = verified)."""
499 size = os.path.getsize(src)
500 mtime_ns = os.stat(src).st_mtime_ns
501 part_size = plan_part_size(size, part_mb)
502 n_parts = max(1, -(-size // part_size))
503 log(f"uploading {src} ({size / 1e9:.2f} GB) to s3://{bucket}/{key}: "
504 f"{n_parts} part(s) of {part_size // MIB} MiB, {concurrency} in flight")
505
506 state = State(state_path)
507 old = state.load() if resume else None
508 identity = {"bucket": bucket, "key": key, "size": size, "mtime_ns": mtime_ns, "part_size": part_size}
509 done = {} # part number -> etag already on the server
510 upload_id = None
511 if old and all(old.get(k) == v for k, v in identity.items()) and old.get("upload_id"):
512 upload_id = old["upload_id"]
513 try:
514 server = list_all_parts(s3, bucket, key, upload_id)
515 except Exception as e:
516 if error_code(e) != "NoSuchUpload":
517 raise
518 # Gone: either completed (a crash after CompleteMultipartUpload) or
519 # expired/aborted. Completed with the right bytes means nothing to do.
520 head = head_or_none(s3, bucket, key)
521 want = expected_sha or old.get("sha256")
522 if head is not None and int(head["ContentLength"]) == size and want and server_sha(head) == want:
523 log(f" previous upload {upload_id} already completed: s3://{bucket}/{key} has "
524 f"{size} bytes, sha256 {want}")
525 state.remove()
526 return 0
527 log(f" previous upload {upload_id} no longer exists on the server; starting over")
528 upload_id = None
529 else:
530 # Keep a server part only if its size is right and its ETag is the MD5
531 # of the local bytes. Parts the state file recorded are trusted by ETag;
532 # parts it missed (crash between upload and save) are re-hashed.
533 recorded = old.get("parts", {})
534 fd = open_ro(src)
535 try:
536 for n, (psize, etag) in sorted(server.items()):
537 if n > n_parts:
538 continue
539 want = min(part_size, size - (n - 1) * part_size)
540 if psize != want:
541 continue
542 if recorded.get(str(n)) == etag:
543 done[n] = etag
544 elif f'"{hashlib.md5(read_part(fd, n, part_size, size)).hexdigest()}"' == etag:
545 done[n] = etag
546 finally:
547 os.close(fd)
548 if old.get("sha256") and expected_sha and old["sha256"] != expected_sha:
549 log(" expected hash changed since the interrupted run; aborting it and starting over")
550 try:
551 s3.abort_multipart_upload(Bucket=bucket, Key=key, UploadId=upload_id)
552 except Exception as e:
553 log(f" (abort failed: {e}; R2 expires it on its own)")
554 upload_id, done = None, {}
555 else:
556 expected_sha = expected_sha or old.get("sha256")
557 log(f" resuming upload {upload_id}: {len(done)}/{n_parts} part(s) already on the server")
558 elif old and old.get("upload_id"):
559 log(f" state file {state_path} is for a different file/key/part size; aborting that upload")
560 try:
561 s3.abort_multipart_upload(Bucket=old["bucket"], Key=old["key"], UploadId=old["upload_id"])
562 except Exception as e:
563 log(f" (abort of the stale upload failed: {e}; R2 expires it on its own)")
564
565 if upload_id is None:
566 if expected_sha is None and verify_local:
567 # Without a sidecar the hash has to be known up front to ride the
568 # create call as metadata.
569 log(" no .sha256 sidecar: hashing the file first")
570 t0 = time.time()
571 expected_sha = sha256_file(src)
572 log(f" sha256 {expected_sha} ({time.time() - t0:.0f} s)")
573 meta = {META_SHA: expected_sha} if expected_sha else {}
574 upload_id = s3.create_multipart_upload(Bucket=bucket, Key=key, Metadata=meta)["UploadId"]
575 state.start(**identity, upload_id=upload_id, sha256=expected_sha)
576 log(f" started multipart upload {upload_id}")
577 else:
578 state.data = {**old, "parts": {str(n): e for n, e in done.items()}, "sha256": expected_sha}
579 state.save()
580
581 # The whole-file SHA-256, read sequentially beside the part workers
582 # (hashlib releases the GIL on large updates).
583 hash_result = {}
584
585 def hash_whole():
586 try:
587 hash_result["sha"] = sha256_file(src)
588 except Exception as e: # reported at the join
589 hash_result["err"] = e
590
591 hasher = threading.Thread(target=hash_whole, daemon=True) if verify_local else None
592 if hasher:
593 hasher.start()
594
595 todo = [n for n in range(1, n_parts + 1) if n not in done]
596 lock = threading.Lock()
597 already = sum(min(part_size, size - (n - 1) * part_size) for n in done)
598 sent = [already]
599 last_mark = [already]
600 t0 = time.time()
601 fd = open_ro(src)
602
603 def send(n: int) -> str:
604 body = read_part(fd, n, part_size, size)
605 md5 = hashlib.md5(body)
606 b64 = base64.b64encode(md5.digest()).decode()
607 want_etag = f'"{md5.hexdigest()}"'
608 delay = RETRY_BASE_S
609 for attempt in range(1, PART_ATTEMPTS + 1):
610 try:
611 etag = s3.upload_part(Bucket=bucket, Key=key, UploadId=upload_id, PartNumber=n,
612 Body=body, ContentMD5=b64)["ETag"]
613 if etag.lower() != want_etag:
614 raise IOError(f"part {n}: server ETag {etag} is not the local MD5 {want_etag}")
615 break
616 except Exception as e:
617 if attempt == PART_ATTEMPTS or error_code(e) == "NoSuchUpload":
618 raise
619 log(f" part {n} attempt {attempt} failed ({e}); retrying in {delay:.0f} s")
620 time.sleep(delay + random.random() * min(delay, 1.0))
621 delay = min(delay * 2, 60)
622 state.part_done(n, etag)
623 with lock:
624 sent[0] += len(body)
625 if sent[0] - last_mark[0] >= 1_000_000_000 or sent[0] >= size:
626 last_mark[0] = sent[0]
627 rate = (sent[0] - already) / max(time.time() - t0, 1e-6)
628 eta = (size - sent[0]) / rate if rate > 0 else 0
629 log(f" {sent[0] / 1e9:.1f}/{size / 1e9:.1f} GB ({100.0 * sent[0] / size:.1f}%) "
630 f"{rate / 1e6:.0f} MB/s, ETA {eta / 60:.1f} min")
631 return etag
632
633 failed = None
634 try:
635 with ThreadPoolExecutor(max_workers=concurrency) as pool:
636 futures = {pool.submit(send, n): n for n in todo}
637 for fut in as_completed(futures):
638 n = futures[fut]
639 try:
640 done[n] = fut.result()
641 except Exception as e:
642 failed = failed or (n, e)
643 for other in futures:
644 other.cancel()
645 finally:
646 os.close(fd)
647 if failed:
648 log(f"UPLOAD FAILED at part {failed[0]}: {failed[1]}")
649 log(f" {len(done)}/{n_parts} part(s) are on the server; rerun the same command to resume "
650 f"(state: {state_path})")
651 return 1
652
653 if hasher:
654 hasher.join()
655 if "err" in hash_result:
656 log(f"UPLOAD FAILED: could not hash {src}: {hash_result['err']}")
657 return 1
658 local_sha = hash_result["sha"]
659 if expected_sha and local_sha != expected_sha:
660 log(f"HASH MISMATCH: {src} hashes to {local_sha}, but the build recorded {expected_sha}.")
661 log(" The local copy is not the file the build produced; aborting the upload so nothing is published.")
662 try:
663 s3.abort_multipart_upload(Bucket=bucket, Key=key, UploadId=upload_id)
664 finally:
665 state.remove()
666 return 3
667 expected_sha = expected_sha or local_sha
668 log(f" local sha256 {local_sha} verified")
669
670 parts = [{"PartNumber": n, "ETag": done[n]} for n in range(1, n_parts + 1)]
671 s3.complete_multipart_upload(Bucket=bucket, Key=key, UploadId=upload_id,
672 MultipartUpload={"Parts": parts})
673 # The upload id is consumed either way; the HEAD below decides the exit code.
674 state.remove()
675 head = s3.head_object(Bucket=bucket, Key=key)
676 remote, rsha = int(head["ContentLength"]), server_sha(head)
677 log(f"done. remote size {remote} bytes, local {size} bytes; remote sha256 {rsha}")
678 if remote != size:
679 log("SIZE MISMATCH after upload")
680 return 2
681 if expected_sha and rsha != expected_sha:
682 log(f"HASH MISMATCH after upload: server records {rsha}, expected {expected_sha}")
683 return 2
684 return 0
685
686
687def put_small(s3, src: str, bucket: str, key: str, sha: str) -> None:
688 with open(src, "rb") as f:
689 body = f.read()
690 md5 = base64.b64encode(hashlib.md5(body).digest()).decode()
691 s3.put_object(Bucket=bucket, Key=key, Body=body, ContentMD5=md5, Metadata={META_SHA: sha})
692
693
694# --------------------------------------------------------------------------
695# Entry points
696# --------------------------------------------------------------------------
697
698def upload_base(argv: list) -> int:
699 ap = argparse.ArgumentParser(prog="upload_planet.py", description="Upload a planet archive to R2.")
700 ap.add_argument("src", help="local file, normally world.mamaps")
701 ap.add_argument("--key", default=KEY, help=f"object key (default {KEY})")
702 ap.add_argument("--sha256", default=None,
703 help="expected SHA-256 (default: read <src>.sha256 if present)")
704 ap.add_argument("--state-file", default=None,
705 help="resume record (default <src>.upload-state.json)")
706 ap.add_argument("--no-resume", action="store_true", help="ignore any saved state and start over")
707 ap.add_argument("--no-verify-local", action="store_true",
708 help="skip the whole-file SHA-256 (the server check then uses --sha256/sidecar only)")
709 add_transfer_args(ap)
710 args = ap.parse_args(argv)
711 if not os.path.isfile(args.src):
712 log(f"no such file: {args.src}")
713 return 2
714 part_mb, conc = transfer_settings(args)
715 expected = args.sha256.lower() if args.sha256 else read_sidecar(args.src + ".sha256", os.path.basename(args.src))
716 if expected:
717 log(f"expected sha256 {expected}" + ("" if args.sha256 else f" (from {args.src}.sha256)"))
718 state_path = args.state_file or args.src + ".upload-state.json"
719 s3 = dry_run_client(state_path) if args.dry_run else make_client(conc)
720 if args.dry_run:
721 log("DRY RUN: no network calls; fake bucket at " + state_path + ".dryrun-bucket.json")
722 return multipart_upload(s3, args.src, BUCKET, args.key, part_mb, conc, state_path,
723 expected_sha=expected, resume=not args.no_resume,
724 verify_local=not args.no_verify_local)
725
726
727def publish_manifest(argv: list) -> int:
728 """Upload overlay segments + write planet3.manifest.json.
729
730 Args: <overlay-dir> --overlay-seq N --base-build-id HEX [--base-len N]
731 The overlay dir holds overlay-*.mamaps (from mamaps_overlay) whose
732 descriptor overlay.json carries the overlay_build_id. Segments upload
733 to overlays/<seq>/overlay-SSSS.mamaps; the manifest lists their CDN
734 URLs + lengths + SHA-256. Sections (chunked sidecars) ride the same
735 manifest when present as <kind>.section files (not yet emitted).
736
737 Server-side vs local: a segment R2 already holds with the same size and
738 x-amz-meta-sha256 is kept, not re-uploaded; every segment is HEAD-checked
739 (size + stored hash == local hash) before the manifest is written; and the
740 base the manifest pins is HEAD-checked against --base-len / --base-sha256.
741 """
742 ap = argparse.ArgumentParser(prog="upload_planet.py --manifest")
743 ap.add_argument("overlay_dir")
744 ap.add_argument("--overlay-seq", type=int, required=True)
745 ap.add_argument("--base-build-id", required=True,
746 help="hex base build_id the overlay applies to, e.g. 0x0355...")
747 ap.add_argument("--base-len", type=int, default=None,
748 help="base length in bytes (else read from overlay.json sidecar)")
749 ap.add_argument("--base-sha256", default=None,
750 help="expected SHA-256 of the base on R2 (checked against its x-amz-meta-sha256)")
751 add_key_args(ap)
752 add_transfer_args(ap)
753 args = ap.parse_args(argv)
754 part_mb, conc = transfer_settings(args)
755 base_key, mkey = args.key, manifest_key(args)
756 overlay_dir = args.overlay_dir
757 descriptor_path = os.path.join(overlay_dir, "overlay.json")
758 try:
759 with open(descriptor_path) as f:
760 descriptor = json.load(f)
761 except (OSError, ValueError) as e:
762 log(f"cannot read {descriptor_path}: {e} (run mamaps_overlay first)")
763 return 2
764 state_dir = os.path.join(overlay_dir, ".upload-state")
765 if args.dry_run:
766 os.makedirs(state_dir, exist_ok=True)
767 s3 = dry_run_client(os.path.join(state_dir, "manifest"))
768 log("DRY RUN: no network calls")
769 else:
770 s3 = make_client(conc)
771
772 base_len = args.base_len if args.base_len is not None else descriptor.get("base_len")
773 base_head = head_or_none(s3, BUCKET, base_key)
774 if base_head is None:
775 log(f"WARN: s3://{BUCKET}/{base_key} does not exist; the manifest would pin a missing base")
776 if not args.dry_run:
777 return 2
778 else:
779 blen, bsha = int(base_head["ContentLength"]), server_sha(base_head)
780 log(f"base on server: {blen} bytes, sha256 {bsha}")
781 if base_len and blen != int(base_len):
782 log(f"BASE MISMATCH: server base is {blen} bytes, the overlay expects {base_len}")
783 return 2
784 if args.base_sha256 and bsha != args.base_sha256.lower():
785 log(f"BASE MISMATCH: server base sha256 {bsha}, expected {args.base_sha256.lower()}")
786 return 2
787
788 segments = []
789 for name in sorted(os.listdir(overlay_dir)):
790 if not (name.startswith("overlay-") and name.endswith(".mamaps")):
791 continue
792 local = os.path.join(overlay_dir, name)
793 key = f"overlays/{args.overlay_seq:04d}/{name}"
794 size = os.path.getsize(local)
795 digest = sha256_file(local)
796 head = head_or_none(s3, BUCKET, key)
797 if head is not None and int(head["ContentLength"]) == size and server_sha(head) == digest:
798 log(f"kept s3://{BUCKET}/{key}: server already holds it (size + sha256 match)")
799 else:
800 if head is not None:
801 log(f"replacing s3://{BUCKET}/{key}: server has {head['ContentLength']} bytes, "
802 f"sha256 {server_sha(head)}; local {size} bytes, {digest}")
803 try:
804 if size <= plan_part_size(size, part_mb):
805 log(f"uploading {local} ({size / 1e6:.1f} MB) to s3://{BUCKET}/{key}")
806 put_small(s3, local, BUCKET, key, digest)
807 else:
808 rc = multipart_upload(s3, local, BUCKET, key, part_mb, conc,
809 os.path.join(state_dir, name + ".json") if args.dry_run
810 else local + ".upload-state.json",
811 expected_sha=digest)
812 if rc != 0:
813 return rc
814 except Exception as e:
815 log(f"UPLOAD FAILED: {e}")
816 return 1
817 head = s3.head_object(Bucket=BUCKET, Key=key)
818 remote, rsha = int(head["ContentLength"]), server_sha(head)
819 if remote != size or rsha != digest:
820 log(f"MISMATCH for {key}: server {remote} bytes / sha256 {rsha}; local {size} / {digest}")
821 return 2
822 seq = int(name[len("overlay-"):len("overlay-") + 4])
823 segments.append({
824 "url": f"{CDN}/{key}",
825 "len": size,
826 "sha256": digest,
827 "seq": seq,
828 })
829 if not segments:
830 log(f"no overlay-*.mamaps in {overlay_dir}")
831 return 2
832 tombstones = descriptor.get("tombstones", [])
833 manifest = {
834 "version": MANIFEST_VERSION,
835 "base": {
836 "url": f"{CDN}/{base_key}",
837 "build_id": args.base_build_id,
838 "len": args.base_len or 0,
839 },
840 "overlay_seq": args.overlay_seq,
841 "overlay_build_id": descriptor.get("overlay_build_id", "0x0"),
842 "segments": segments,
843 "sections": [],
844 "tombstones": tombstones,
845 "min_client": MIN_CLIENT_COMPAT,
846 }
847 body = json.dumps(manifest, indent=1).encode()
848 s3.put_object(Bucket=BUCKET, Key=mkey, Body=body,
849 ContentType="application/json")
850 log(f"wrote s3://{BUCKET}/{mkey} "
851 f"({len(segments)} segments, overlay_build_id={manifest['overlay_build_id']})")
852 return 0
853
854
855def publish_rebase(argv: list) -> int:
856 """Publish a consolidation: a fresh full base becomes the world, and the
857 overlay stack resets to empty.
858
859 Run quarterly, or when the stacked overlays exceed ~20% of the base or
860 the sequence depth passes 3. The new base uploads exactly like a normal
861 planet publish (same KEY, new bytes, new build_id); the manifest then
862 pins it with zero segments, so clients do one background full download
863 and drop their old segments. No client-side rewrite pass exists by
864 design (the no-2x guarantee stays trivially true).
865
866 Args: --overlay-seq N --base-build-id HEX --base-len N [--dry-run]
867 (N continues the sequence; segments/tombstones/sections are empty.)
868 """
869 ap = argparse.ArgumentParser(prog="upload_planet.py --rebase")
870 ap.add_argument("--overlay-seq", type=int, required=True)
871 ap.add_argument("--base-build-id", required=True)
872 ap.add_argument("--base-len", type=int, required=True)
873 ap.add_argument("--base-sha256", default=None,
874 help="expected SHA-256 of the base on R2 (checked against its x-amz-meta-sha256)")
875 ap.add_argument("--dry-run", action="store_true")
876 add_key_args(ap)
877 args = ap.parse_args(argv)
878 base_key, mkey = args.key, manifest_key(args)
879 s3 = FakeS3() if args.dry_run else make_client(DEFAULT_CONCURRENCY)
880 if not args.dry_run:
881 # Never pin a base that is missing or is not the file we think it is.
882 head = head_or_none(s3, BUCKET, base_key)
883 if head is None:
884 log(f"s3://{BUCKET}/{base_key} does not exist; refusing to write a manifest that pins it")
885 return 2
886 blen, bsha = int(head["ContentLength"]), server_sha(head)
887 log(f"base on server: {blen} bytes, sha256 {bsha}")
888 if blen != args.base_len:
889 log(f"BASE MISMATCH: server base is {blen} bytes, --base-len says {args.base_len}")
890 return 2
891 if args.base_sha256 and bsha != args.base_sha256.lower():
892 log(f"BASE MISMATCH: server base sha256 {bsha}, expected {args.base_sha256.lower()}")
893 return 2
894 manifest = {
895 "version": MANIFEST_VERSION,
896 "base": {
897 "url": f"{CDN}/{base_key}",
898 "build_id": args.base_build_id,
899 "len": args.base_len,
900 },
901 "overlay_seq": args.overlay_seq,
902 "overlay_build_id": "0x0",
903 "segments": [],
904 "sections": [],
905 "tombstones": [],
906 "min_client": MIN_CLIENT_COMPAT,
907 }
908 body = json.dumps(manifest, indent=1).encode()
909 s3.put_object(Bucket=BUCKET, Key=mkey, Body=body,
910 ContentType="application/json")
911 log(f"{'DRY RUN: would write' if args.dry_run else 'wrote'} s3://{BUCKET}/{mkey} "
912 f"rebase seq={args.overlay_seq} (empty overlay; clients refresh the base once)")
913 return 0
914
915
916def main() -> int:
917 if len(sys.argv) >= 2 and sys.argv[1] == "--manifest":
918 return publish_manifest(sys.argv[2:])
919 if len(sys.argv) >= 2 and sys.argv[1] == "--rebase":
920 return publish_rebase(sys.argv[2:])
921 if len(sys.argv) < 2:
922 log(f"usage: {os.path.basename(sys.argv[0])} <local-file> [--key K] [--dry-run] [--part-size-mb N] "
923 f"[--concurrency N] [--sha256 HEX] [--state-file PATH] [--no-resume]")
924 log(f" or: {os.path.basename(sys.argv[0])} --manifest <overlay-dir> --overlay-seq N "
925 f"--base-build-id HEX [--base-len N] [--base-sha256 HEX] [--key K] [--manifest-key M] [--dry-run]")
926 log(f" or: {os.path.basename(sys.argv[0])} --rebase --overlay-seq N --base-build-id HEX "
927 f"--base-len N [--base-sha256 HEX] [--key K] [--manifest-key M] [--dry-run]")
928 return 2
929 return upload_base(sys.argv[1:])
930
931
932if __name__ == "__main__":
933 sys.exit(main())