Handle Geofabrik latest redirects with verified dated extracts

This commit is contained in:
dasemu committed 2026-09-30 17:51:00 +02:00
1 parent 6c33d8a6c7
commit 989bcda281
4 files changed
+141 -13

No files matched your search

+81 -10
View File
@@ -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'
+57
View File
@@ -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 = '<a href="andorra-260929.osm.pbf">PBF</a><a href="andorra-260929.osm.pbf.md5">MD5</a>'
def test_selects_newest_valid_matching_pair(self):
html = self.html + '<a href="andorra-260928.osm.pbf">old</a><a href="andorra-260928.osm.pbf.md5">old md5</a>'
html += '<a href="andorra-261332.osm.pbf">invalid</a><a href="andorra-261332.osm.pbf.md5">md5</a>'
html += '<a href="andorra-261001.osm.pbf">no checksum</a>'
html += '<a href="https://evil.example/andorra-261002.osm.pbf">evil</a><a href="https://evil.example/andorra-261002.osm.pbf.md5">evil md5</a>'
html += '<a href="france-261002.osm.pbf">other region</a><a href="france-261002.osm.pbf.md5">other md5</a>'
self.assertEqual(global_regions.dated_extract(self.latest, html), self.dated)
with self.assertRaises(ValueError):
global_regions.dated_extract(self.latest, '<a href="andorra-261001.osm.pbf">no checksum</a>')
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)