diff --git a/.github/workflows/offline-regions.yml b/.github/workflows/offline-regions.yml
index 7d936cd..6fcb310 100644
--- a/.github/workflows/offline-regions.yml
+++ b/.github/workflows/offline-regions.yml
@@ -1,7 +1,7 @@
name: Build worldwide offline regions
on:
push:
- tags: ['offline-bootstrap-andorra']
+ tags: ['offline-bootstrap-andorra', 'offline-bootstrap-andorra-*']
workflow_dispatch:
inputs:
regions:
diff --git a/docs/GLOBAL_OFFLINE.md b/docs/GLOBAL_OFFLINE.md
index f21fe84..299c11c 100644
--- a/docs/GLOBAL_OFFLINE.md
+++ b/docs/GLOBAL_OFFLINE.md
@@ -6,7 +6,7 @@ The app installs individual `.navframe` packages containing a PMTiles map, a SQL
In `Dasemu/NavFrame`, open **Actions → Build worldwide offline regions → Run workflow**. Enter Geofabrik IDs such as `andorra,act,cantabria,us/california`. First run with **publish = false** to inspect artifacts; run with **publish = true** to publish packages. Each run builds at most 32 independent regions, with two concurrent builders and a 330-minute timeout per builder. No planet download or full-world local build is performed.
-One-time bootstrap with SSH push access (no local GitHub CLI/token required): after pushing the project to the default branch, create and push the exact tag below. Only this tag triggers an automatic **Andorra** build with publication enabled; other tag or branch pushes do not trigger the offline builder. The catalog becomes available after that workflow succeeds.
+One-time bootstrap with SSH push access (no local GitHub CLI/token required): after pushing the project to the default branch, create and push the exact tag below. Only this tag and `offline-bootstrap-andorra-*` retry tags trigger an automatic **Andorra** build with publication enabled; other tag or branch pushes do not trigger the offline builder. The catalog becomes available after that workflow succeeds. For a retry after fixing a failed run, push a new tag such as `offline-bootstrap-andorra-v2`; preserve existing tags.
```sh
git tag offline-bootstrap-andorra
@@ -29,7 +29,7 @@ curl --fail --location --output planetiler.jar https://github.com/onthegomap/pla
python3 tools/offline/global-regions.py build --region andorra --version 20260930.1 --planetiler-jar planetiler.jar --output build/offline/andorra
```
-`build-region.py` also accepts existing PBF/.poly/PMTiles inputs for network-free builds. Planetiler and POI dependencies are pinned by version. Build provenance records the recipe, upstream PBF SHA-256, coverage SHA-256, Planetiler binary SHA-256 and PBF replication timestamp. Geofabrik's `latest` source URL rotates daily; the downloaded PBF is checked against its official MD5 sidecar, and its actual bytes are identified by SHA-256. A daily rotation during download fails rather than accepting a mismatch. OSM's replication timestamp identifies data freshness, while the package version identifies a publication.
+`build-region.py` also accepts existing PBF/.poly/PMTiles inputs for network-free builds. Planetiler and POI dependencies are pinned by version. Build provenance records the recipe, upstream PBF SHA-256, coverage SHA-256, Planetiler binary SHA-256 and PBF replication timestamp. Geofabrik's `latest` source URL rotates daily; the downloaded PBF is checked against its official MD5 sidecar, and its actual bytes are identified by SHA-256. If the latest link fails (including redirect loops) or its checksum mismatches during daily rotation, the builder reads the bounded official region HTML and selects its newest dated PBF with a matching-basename checksum link. It downloads and verifies that exact pair and records the actual dated extract URL in the manifest. An invalid checksum on the fallback fails the build. OSM's replication timestamp identifies data freshness, while the package version identifies a publication.
## Catalog and publication contract
diff --git a/tools/offline/global-regions.py b/tools/offline/global-regions.py
index 5b155a0..98b1745 100644
--- a/tools/offline/global-regions.py
+++ b/tools/offline/global-regions.py
@@ -2,6 +2,8 @@
"""Discover/build bounded Geofabrik regions and merge immutable catalog fragments."""
import argparse
import hashlib
+from datetime import date
+from html.parser import HTMLParser
import json
import os
from pathlib import Path
@@ -10,6 +12,8 @@ import sqlite3
import subprocess
import sys
from urllib.request import urlopen
+from urllib.error import HTTPError, URLError
+from urllib.parse import urljoin
INDEX = 'https://download.geofabrik.de/index-v1-nogeom.json'
ROOT = Path(__file__).resolve().parents[2]
@@ -22,10 +26,12 @@ def official_url(url):
def download(url, path, maximum):
+ official_url(url)
path.parent.mkdir(parents=True, exist_ok=True)
staging = path.with_suffix(path.suffix + '.part')
try:
with urlopen(url, timeout=120) as source, staging.open('wb') as target:
+ official_url(source.geturl())
if int(source.headers.get('Content-Length', 0)) > maximum:
raise ValueError('Extract exceeds input budget; select a smaller region or larger runner')
total = 0
@@ -39,6 +45,78 @@ def download(url, path, maximum):
staging.unlink(missing_ok=True)
+class ExtractChecksumError(ValueError):
+ """Upstream bytes and their paired checksum do not agree."""
+
+
+def verify_extract(pbf, checksum):
+ fields = checksum.read_text().split()
+ expected = fields[0] if fields else ''
+ digest = hashlib.md5()
+ with pbf.open('rb') as stream:
+ while block := stream.read(1024 * 1024):
+ digest.update(block)
+ if not re.fullmatch(r'[a-fA-F0-9]{32}', expected) or digest.hexdigest() != expected.lower():
+ raise ExtractChecksumError('Geofabrik PBF checksum mismatch')
+
+
+def dated_extract(latest, html):
+ """Choose newest valid dated PBF/checksum pair linked on this region's page."""
+ official_url(latest)
+ if not latest.endswith('-latest.osm.pbf'):
+ raise ValueError('Expected latest extract URL')
+ if len(html.encode('utf-8')) > 2 * 1024 * 1024:
+ raise ValueError('Region HTML exceeds discovery budget')
+ stem = latest.removesuffix('-latest.osm.pbf')
+ page = stem + '.html'
+ links = set()
+
+ class Links(HTMLParser):
+ def handle_starttag(self, tag, attributes):
+ if tag.lower() != 'a':
+ return
+ for key, value in attributes:
+ if key.lower() == 'href' and value and '..' not in value:
+ links.add(urljoin(page, value))
+
+ parser = Links()
+ parser.feed(html)
+ candidates = []
+ pattern = re.compile(re.escape(stem) + r'-(\d{6})\.osm\.pbf')
+ for link in links:
+ match = pattern.fullmatch(link)
+ if match is None or link + '.md5' not in links:
+ continue
+ stamp = match[1]
+ try:
+ when = date(2000 + int(stamp[:2]), int(stamp[2:4]), int(stamp[4:6]))
+ except ValueError:
+ continue
+ candidates.append((when, official_url(link)))
+ if not candidates:
+ raise ValueError('Official region page has no dated PBF/checksum pair')
+ return max(candidates)[1]
+
+
+def download_extract(latest, pbf, checksum, maximum):
+ try:
+ download(latest, pbf, maximum)
+ download(latest + '.md5', checksum, 4096)
+ verify_extract(pbf, checksum)
+ return latest
+ except (URLError, TimeoutError, ExtractChecksumError) as error:
+ print(f'Latest extract unavailable ({error}); resolving official dated extract', file=sys.stderr)
+ if isinstance(error, HTTPError):
+ error.close()
+ page = pbf.parent / 'region-source.html'
+ download(latest.removesuffix('-latest.osm.pbf') + '.html', page, 2 * 1024 * 1024)
+ source = dated_extract(latest, page.read_text(encoding='utf-8'))
+ download(source, pbf, maximum)
+ download(source + '.md5', checksum, 4096)
+ verify_extract(pbf, checksum)
+ return source
+
+
def regions(index):
properties = {f['properties']['id']: f['properties'] for f in index['features']}
result = []
@@ -97,16 +175,8 @@ def build(args, selected):
work = args.output / 'work'
work.mkdir(parents=True, exist_ok=True)
pbf, poly = work / 'region.osm.pbf', work / 'region.poly'
- download(selected['source'], pbf, args.max_input_mib * 1024 * 1024)
checksum = work / 'region.osm.pbf.md5'
- download(selected['source'] + '.md5', checksum, 4096)
- expected = checksum.read_text().split()[0]
- digest = hashlib.md5()
- with pbf.open('rb') as stream:
- while block := stream.read(1024 * 1024):
- digest.update(block)
- if not re.fullmatch(r'[a-fA-F0-9]{32}', expected) or digest.hexdigest() != expected.lower():
- raise ValueError('Geofabrik PBF checksum mismatch (possibly daily rotation); rerun')
+ source_url = download_extract(selected['source'], pbf, checksum, args.max_input_mib * 1024 * 1024)
download(selected['coverage'], poly, 16 * 1024 * 1024)
slug = selected['id'].replace('/', '-')
archive = args.output / f"gf-{slug}-{args.version}.navframe"
@@ -114,7 +184,8 @@ def build(args, selected):
'--id', f"gf-{slug}", '--name', selected['name'], '--version', args.version,
'--pbf', str(pbf), '--coverage-poly', str(poly), '--coverage-url', selected['coverage'],
'--planetiler-jar', str(args.planetiler_jar), '--java-heap', args.java_heap,
- '--source-url', selected['source'], '--output', str(archive), '--work', str(work)], check=True)
+ '--python', sys.executable,
+ '--source-url', source_url, '--output', str(archive), '--work', str(work)], check=True)
if archive.stat().st_size >= args.max_package_mib * 1024 * 1024:
raise ValueError('Package exceeds publication budget; select a smaller region')
catalog_path = args.output / 'regional-catalog.json'
diff --git a/tools/offline/test_global_regions.py b/tools/offline/test_global_regions.py
index 4232be8..5efca09 100644
--- a/tools/offline/test_global_regions.py
+++ b/tools/offline/test_global_regions.py
@@ -1,5 +1,8 @@
import importlib.util
import json
+import hashlib
+from unittest.mock import patch
+from urllib.error import HTTPError
from pathlib import Path
import tempfile
import unittest
@@ -52,3 +55,57 @@ class GlobalPipelineTest(unittest.TestCase):
second.write_text(json.dumps({'schemaVersion': 1, 'regions': [entry]}))
with self.assertRaises(ValueError):
global_regions.merge([first, second])
+
+
+class DatedExtractTest(unittest.TestCase):
+ latest = 'https://download.geofabrik.de/europe/andorra-latest.osm.pbf'
+ dated = 'https://download.geofabrik.de/europe/andorra-260929.osm.pbf'
+ html = 'PBFMD5'
+
+ def test_selects_newest_valid_matching_pair(self):
+ html = self.html + 'oldold md5'
+ html += 'invalidmd5'
+ html += 'no checksum'
+ html += 'evilevil md5'
+ html += 'other regionother md5'
+ self.assertEqual(global_regions.dated_extract(self.latest, html), self.dated)
+ with self.assertRaises(ValueError):
+ global_regions.dated_extract(self.latest, 'no checksum')
+ with self.assertRaises(ValueError):
+ global_regions.dated_extract(self.latest, 'x' * (2 * 1024 * 1024 + 1))
+
+ def test_redirect_loop_fallback_downloads_exact_pair(self):
+ requested = []
+ content = b'OSM test bytes'
+ def fake_download(url, path, maximum):
+ requested.append(url)
+ if url == self.latest:
+ raise HTTPError(url, 301, 'redirect loop', {}, None)
+ if url.endswith('.html'):
+ path.write_text(self.html)
+ elif url == self.dated:
+ path.write_bytes(content)
+ elif url == self.dated + '.md5':
+ path.write_text(hashlib.md5(content).hexdigest() + ' andorra-260929.osm.pbf')
+ else:
+ self.fail('Unexpected download URL: ' + url)
+ with tempfile.TemporaryDirectory() as temporary, patch.object(global_regions, 'download', side_effect=fake_download):
+ root = Path(temporary)
+ actual = global_regions.download_extract(self.latest, root / 'region.osm.pbf', root / 'checksum.md5', 4096)
+ self.assertEqual(actual, self.dated)
+ self.assertEqual(requested[-2:], [self.dated, self.dated + '.md5'])
+
+ def test_size_budget_error_does_not_fallback(self):
+ with patch.object(global_regions, 'download', side_effect=ValueError('input budget')) as downloader:
+ with self.assertRaises(ValueError):
+ global_regions.download_extract(self.latest, Path('unused'), Path('unused.md5'), 1)
+ self.assertEqual(downloader.call_count, 1)
+
+ def test_wrong_dated_checksum_fails(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ pbf, checksum = root / 'region.osm.pbf', root / 'checksum.md5'
+ pbf.write_bytes(b'test')
+ checksum.write_text('0' * 32)
+ with self.assertRaises(global_regions.ExtractChecksumError):
+ global_regions.verify_extract(pbf, checksum)