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

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

upload_planet.py271 lines · 10.2 KiBRaw
1"""Upload any local file to R2 as planet3.mamaps (bucket: maps).
2
3Usage: python upload_planet.py <local-file>
4 python upload_planet.py --manifest <overlay-dir> --overlay-seq N --base-build-id HEX
5Verifies server-side size matches, then deletes nothing local. Progress
6prints every ~1 GB.
7
8Serves https://data.maproj.org/planet3.mamaps, which the apps'
9basemap URLs point at (library/map urls.rs, maps MapTileCache.kt).
10
11The --manifest form publishes a patch-overlay update: it uploads each
12overlay-*.mamaps segment from the overlay dir under overlays/<seq>/,
13then writes planet3.manifest.json (base pin + segment list + hashes).
14The manifest is the only file the client fetches on a check.
15
16SECURITY: credentials/config come from ENVIRONMENT VARIABLES, never baked
17into this file (the analysis/ original carried hardcoded keys and must
18stay gitignored there). Never paste keys on the command line — `export`
19them instead, ideally from a secret store.
20
21Required env:
22 R2_ENDPOINT S3 API endpoint, e.g. https://<ACCOUNT_ID>.r2.cloudflarestorage.com
23 R2_ACCESS_KEY_ID R2 access key id
24 R2_SECRET_ACCESS_KEY R2 secret access key
25Optional env:
26 R2_BUCKET Default: maps
27 R2_CDN Default: https://data.maproj.org (URL prefix written into the manifest)
28"""
29import hashlib
30import json
31import os
32import sys
33import threading
34
35import boto3
36from boto3.s3.transfer import TransferConfig
37
38BUCKET = os.environ.get("R2_BUCKET", "maps")
39KEY = "planet3.mamaps"
40MANIFEST_KEY = "planet3.manifest.json"
41CDN = os.environ.get("R2_CDN", "https://data.maproj.org")
42
43PART_SIZE = 100 * 1024 * 1024 # 100 MB parts, 10-way concurrency
44
45MANIFEST_VERSION = 1
46MIN_CLIENT_COMPAT = 1
47
48
49def main() -> int:
50 if len(sys.argv) >= 2 and sys.argv[1] == "--manifest":
51 return publish_manifest(sys.argv[2:])
52 if len(sys.argv) >= 2 and sys.argv[1] == "--rebase":
53 return publish_rebase(sys.argv[2:])
54 if len(sys.argv) != 2:
55 print(f"usage: {os.path.basename(sys.argv[0])} <local-file>", flush=True)
56 print(f" or: {os.path.basename(sys.argv[0])} --manifest <overlay-dir> --overlay-seq N --base-build-id HEX [--base-len N]", flush=True)
57 print(f" or: {os.path.basename(sys.argv[0])} --rebase --overlay-seq N --base-build-id HEX --base-len N", flush=True)
58 return 2
59 missing = [v for v in ("R2_ENDPOINT", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY")
60 if not os.environ.get(v)]
61 if missing:
62 print(f"missing env: {', '.join(missing)} (see module docstring)", flush=True)
63 return 2
64 src = sys.argv[1]
65 if not os.path.isfile(src):
66 print(f"no such file: {src}", flush=True)
67 return 2
68 size = os.path.getsize(src)
69 print(f"uploading {src} ({size / 1e9:.1f} GB) to s3://{BUCKET}/{KEY}", flush=True)
70
71 s3 = boto3.client(
72 "s3",
73 endpoint_url=os.environ["R2_ENDPOINT"],
74 aws_access_key_id=os.environ["R2_ACCESS_KEY_ID"],
75 aws_secret_access_key=os.environ["R2_SECRET_ACCESS_KEY"],
76 region_name="auto",
77 )
78 config = TransferConfig(
79 multipart_threshold=PART_SIZE,
80 multipart_chunksize=PART_SIZE,
81 max_concurrency=10,
82 use_threads=True,
83 )
84
85 lock = threading.Lock()
86 done = [0]
87 last_mark = [0]
88
89 def progress(n: int) -> None:
90 with lock:
91 done[0] += n
92 gb = done[0] / 1e9
93 if gb - last_mark[0] >= 1.0 or done[0] >= size:
94 last_mark[0] = gb
95 pct = 100.0 * done[0] / size
96 print(f" {gb:.1f}/{size / 1e9:.1f} GB ({pct:.1f}%)", flush=True)
97
98 try:
99 s3.upload_file(src, BUCKET, KEY, Config=config, Callback=progress)
100 except Exception as e:
101 print(f"UPLOAD FAILED: {e}", flush=True)
102 return 1
103
104 remote = s3.head_object(Bucket=BUCKET, Key=KEY)["ContentLength"]
105 print(f"done. remote size {remote} bytes, local {size} bytes", flush=True)
106 return 0 if remote == size else 2
107
108
109def publish_manifest(argv: list) -> int:
110 """Upload overlay segments + write planet3.manifest.json.
111
112 Args: <overlay-dir> --overlay-seq N --base-build-id HEX [--base-len N]
113 The overlay dir holds overlay-*.mamaps (from mamaps_overlay) whose
114 descriptor overlay.json carries the overlay_build_id. Segments upload
115 to overlays/<seq>/overlay-SSSS.mamaps; the manifest lists their CDN
116 URLs + lengths + SHA-256. Sections (chunked sidecars) ride the same
117 manifest when present as <kind>.section files (not yet emitted).
118 """
119 import argparse
120 ap = argparse.ArgumentParser()
121 ap.add_argument("overlay_dir")
122 ap.add_argument("--overlay-seq", type=int, required=True)
123 ap.add_argument("--base-build-id", required=True,
124 help="hex base build_id the overlay applies to, e.g. 0x0355...")
125 ap.add_argument("--base-len", type=int, default=None,
126 help="base length in bytes (else read from overlay.json sidecar)")
127 args = ap.parse_args(argv)
128 missing = [v for v in ("R2_ENDPOINT", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY")
129 if not os.environ.get(v)]
130 if missing:
131 print(f"missing env: {', '.join(missing)} (see module docstring)", flush=True)
132 return 2
133 overlay_dir = args.overlay_dir
134 descriptor_path = os.path.join(overlay_dir, "overlay.json")
135 try:
136 descriptor = json.load(open(descriptor_path))
137 except (OSError, ValueError) as e:
138 print(f"cannot read {descriptor_path}: {e} (run mamaps_overlay first)", flush=True)
139 return 2
140 s3 = boto3.client(
141 "s3",
142 endpoint_url=os.environ["R2_ENDPOINT"],
143 aws_access_key_id=os.environ["R2_ACCESS_KEY_ID"],
144 aws_secret_access_key=os.environ["R2_SECRET_ACCESS_KEY"],
145 region_name="auto",
146 )
147 config = TransferConfig(
148 multipart_threshold=PART_SIZE,
149 multipart_chunksize=PART_SIZE,
150 max_concurrency=10,
151 use_threads=True,
152 )
153 segments = []
154 for name in sorted(os.listdir(overlay_dir)):
155 if not (name.startswith("overlay-") and name.endswith(".mamaps")):
156 continue
157 local = os.path.join(overlay_dir, name)
158 key = f"overlays/{args.overlay_seq:04d}/{name}"
159 size = os.path.getsize(local)
160 print(f"uploading {local} ({size / 1e6:.1f} MB) to s3://{BUCKET}/{key}", flush=True)
161 try:
162 s3.upload_file(local, BUCKET, key, Config=config)
163 except Exception as e:
164 print(f"UPLOAD FAILED: {e}", flush=True)
165 return 1
166 remote = s3.head_object(Bucket=BUCKET, Key=key)["ContentLength"]
167 if remote != size:
168 print(f"size mismatch for {key}: remote {remote} vs local {size}", flush=True)
169 return 2
170 digest = sha256_file(local)
171 seq = int(name[len("overlay-"):len("overlay-") + 4])
172 segments.append({
173 "url": f"{CDN}/{key}",
174 "len": size,
175 "sha256": digest,
176 "seq": seq,
177 })
178 if not segments:
179 print(f"no overlay-*.mamaps in {overlay_dir}", flush=True)
180 return 2
181 tombstones = descriptor.get("tombstones", [])
182 manifest = {
183 "version": MANIFEST_VERSION,
184 "base": {
185 "url": f"{CDN}/{KEY}",
186 "build_id": args.base_build_id,
187 "len": args.base_len or 0,
188 },
189 "overlay_seq": args.overlay_seq,
190 "overlay_build_id": descriptor.get("overlay_build_id", "0x0"),
191 "segments": segments,
192 "sections": [],
193 "tombstones": tombstones,
194 "min_client": MIN_CLIENT_COMPAT,
195 }
196 body = json.dumps(manifest, indent=1).encode()
197 s3.put_object(Bucket=BUCKET, Key=MANIFEST_KEY, Body=body,
198 ContentType="application/json")
199 print(f"wrote s3://{BUCKET}/{MANIFEST_KEY} "
200 f"({len(segments)} segments, overlay_build_id={manifest['overlay_build_id']})",
201 flush=True)
202 return 0
203
204
205def sha256_file(path: str) -> str:
206 h = hashlib.sha256()
207 with open(path, "rb") as f:
208 while True:
209 chunk = f.read(1 << 20)
210 if not chunk:
211 break
212 h.update(chunk)
213 return h.hexdigest()
214
215
216def publish_rebase(argv: list) -> int:
217 """Publish a consolidation: a fresh full base becomes the world, and the
218 overlay stack resets to empty.
219
220 Run quarterly, or when the stacked overlays exceed ~20% of the base or
221 the sequence depth passes 3. The new base uploads exactly like a normal
222 planet publish (same KEY, new bytes, new build_id); the manifest then
223 pins it with zero segments, so clients do one background full download
224 and drop their old segments. No client-side rewrite pass exists by
225 design (the no-2x guarantee stays trivially true).
226
227 Args: --overlay-seq N --base-build-id HEX --base-len N
228 (N continues the sequence; segments/tombstones/sections are empty.)
229 """
230 import argparse
231 ap = argparse.ArgumentParser()
232 ap.add_argument("--overlay-seq", type=int, required=True)
233 ap.add_argument("--base-build-id", required=True)
234 ap.add_argument("--base-len", type=int, required=True)
235 args = ap.parse_args(argv)
236 missing = [v for v in ("R2_ENDPOINT", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY")
237 if not os.environ.get(v)]
238 if missing:
239 print(f"missing env: {', '.join(missing)} (see module docstring)", flush=True)
240 return 2
241 s3 = boto3.client(
242 "s3",
243 endpoint_url=os.environ["R2_ENDPOINT"],
244 aws_access_key_id=os.environ["R2_ACCESS_KEY_ID"],
245 aws_secret_access_key=os.environ["R2_SECRET_ACCESS_KEY"],
246 region_name="auto",
247 )
248 manifest = {
249 "version": MANIFEST_VERSION,
250 "base": {
251 "url": f"{CDN}/{KEY}",
252 "build_id": args.base_build_id,
253 "len": args.base_len,
254 },
255 "overlay_seq": args.overlay_seq,
256 "overlay_build_id": "0x0",
257 "segments": [],
258 "sections": [],
259 "tombstones": [],
260 "min_client": MIN_CLIENT_COMPAT,
261 }
262 body = json.dumps(manifest, indent=1).encode()
263 s3.put_object(Bucket=BUCKET, Key=MANIFEST_KEY, Body=body,
264 ContentType="application/json")
265 print(f"wrote s3://{BUCKET}/{MANIFEST_KEY} rebase seq={args.overlay_seq} "
266 f"(empty overlay; clients refresh the base once)", flush=True)
267 return 0
268
269
270if __name__ == "__main__":
271 sys.exit(main())