Modern Apps git

← Modern-Apps.git

maps: resolve world transit feeds through transitland-atlas for MOTIS ids

Commit
8452e8cd8122338c1516527edc342c58c5389132
Author
vayun-mathur <[email protected]>
When
2026-08-21 06:57 UTC (3 months ago)
Parents
8f38d9c

Diff

scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex ba6fe1d4b3..85f42ca801 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -177,7 +177,7 @@ mutually consistent (same POI set, same coordinates). See | `build_admin_layers.sh` | `admin_city`: **`--engine-city rust`** (default) is `osm_extract`'s own ring assembler → `tile_polygons`, cargo-only; `legacy` is osmium → `normalize_admin.py` → tippecanoe. `admin_country`/`admin_region`: Natural Earth → `normalize_admin.py` → tippecanoe, with **no rust engine** — OSM cannot supply them. `--only-city` builds the one admin layer a cargo-only box can | | `build_transit_stops_layer.sh` | GTFS dirs → `gtfs_ingest` `transit_stops` → geojsonseq → `tile_build` `tile_points` → `transit_stops.pmtiles`. **No tippecanoe, no osmium** | | `build_transit_stops_layer.ps1` | **Windows** entry point for the same layer (cargo-only) |-| `gtfs_ingest/` | Rust GTFS crate (detached): `gtfs_ingest` (the on-device `.transit` pack) and `transit_stops` (the basemap stop layer). TRX2 on-disk format documented in `src/index.rs` |+| `gtfs_ingest/` | Rust GTFS crate (detached, **zero dependencies**): `gtfs_ingest` (the on-device `.transit` pack), `transit_stops` (the basemap stop layer) and `resolve_feeds` (resolves the Transitous registry against transitland-atlas into a download plan whose feeds carry MOTIS ids). TRX2 on-disk format documented in `src/index.rs`, the resolution rules in `src/registry.rs` | | `tile_build/` | Rust MVT + PMTiles v3 crate (detached), **replacing tippecanoe, tile-join and go-pmtiles**. Bins: `tile_points` / `tile_lines` / `tile_polygons` (one per geometry kind), `tile_join` (merge archives), `pmtiles_extract` (subset by bbox, zoom and layer — the `go-pmtiles extract` replacement and the admin layer lift), `pmtiles_dump` (canonical text dump, for the differential harness). Library: `geojson` (the shared GeoJSONSeq reader), `geom` (web-mercator projection, tile ranges, quantisation), `clip` (Liang-Barsky for lines, Sutherland-Hodgman for polygons), `simplify` (Douglas-Peucker in integer tile coordinates), `pyramid` (the tile pyramid driver and the drop policy), `mvt` (line and polygon encoders beside the opaque passthrough that keeps `tile_join` lossless). Container layout documented in `src/pmtiles.rs`, the pipeline order in `src/geom.rs`, the drop policy in `src/pyramid.rs` | | `publish_r2.sh` | Upload built artifacts to Cloudflare R2 (creds from env vars only) | | `normalize_safety.py` | OSM tags → `safety` layer schema (pure stdlib, unit-tested). **Superseded** by `osm_ingest/src/safety.rs`; kept as the contract of record and as `--engine legacy` for the differential harness |@@ -291,17 +291,33 @@ Consequences:  ### 4. World transit is a large step up in cost -Today's `world.transit` is built from `.url` fields alone, which silently drops-most US feeds — 38 of California's 49 sources — because they are referenced by-`transitland-atlas-id` with no URL. Resolving those references the way-`build_ca_transit.ps1` does turns 27 feeds and 18 MB into hundreds of feeds and-many GB of downloads. **A `--region` filter is mandatory** for staging: validate-on California, then a few regions, then the world.--The two producers also differ in what they can emit. Only the DMFR-resolving-path knows each feed's original source name, so only it can write the three-field-manifest that gives stops their MOTIS ids — and without those, live delays cannot-be matched to a stop.+`build_world_transit.sh` used to scrape `url` fields out of the registry, which+silently dropped every source referenced only by `transitland-atlas-id` — **38 of+California's 49**. Its feed names were positional (`us_ca_0`, `us_ca_1`, …), so its+manifest was two-field, so nothing carried a **MOTIS prefix** — and without those,+live delays cannot be matched to a stop.++`gtfs_ingest`'s `resolve_feeds` now does the atlas resolution `build_ca_transit.ps1`+pioneered, across every `feeds/*.json`, and emits the three-field manifest. Two+rules in it are worth knowing, because both were bugs in the shell version:++* **The atlas entry is resolved before any URL is chosen**, even when the registry+  supplies a `url-override`. An agency is usually listed twice — once `spec: gtfs`,+  once `spec: gtfs-rt` — and only the atlas entry distinguishes them. Trusting the+  override first lets a realtime endpoint win the dedup and knock the real timetable+  out of the build.+* **Realtime detection looks at the URL path, not the whole URL**, and a `.zip` is+  definitively static. The old `*realtime*` glob matched whole URLs, so Golden Gate+  Transit's perfectly good schedule zip was thrown away for being served from+  `realtime.goldengate.org`.++The cost: hundreds of feeds and many GB of downloads, against the 18.9 MB pack the+`.url`-only scrape produced. **`--region` and `--max-feeds` are how you stage it** —+California first (known-good), then a few regions, then the world — and+`--resolve-only` shows the plan without fetching a byte. Downloads are+content-addressed on the URL rather than the feed name, because feed names shift+when the registry updates and URLs do not, so a re-run with a different `--region`+re-uses everything it already has.  ### 5. Credential env vars are not uniform 
scripts/maps/build_world_transit.sh
diff --git a/scripts/maps/build_world_transit.sh b/scripts/maps/build_world_transit.shindex 0b15ec4932..c030cec3fc 100644--- a/scripts/maps/build_world_transit.sh+++ b/scripts/maps/build_world_transit.sh@@ -2,56 +2,73 @@ set -euo pipefail  # build_world_transit.sh — build the single global offline transit index-# (`world.transit`) by MERGING every GTFS feed in the Transitous registry into-# one TRX2 pack via `scripts/maps/gtfs_ingest`, then (optionally) publish it to-# R2 (served at data.vayunmathur.com/world.transit).+# (`world.transit`) by resolving the Transitous registry against+# transitland-atlas, downloading every static GTFS feed, and merging them into one+# TRX2 pack via `scripts/maps/gtfs_ingest`. #-# This mirrors the "single global graph" decision for roads: the app downloads-# ONE transit pack on first open (see MainActivity's InitialDownloadChecker) and+# This mirrors the "single global graph" decision for roads: the app downloads ONE+# transit pack on first open (see MainActivity's InitialDownloadChecker) and # `OfflineRouter` just iterates `*.transit` — no per-zone logic. #-# This is a HEAVY data job (tens of GB downloaded, GBs of unzipped GTFS). Run it-# in WSL / Linux with plenty of disk. VALIDATE ON A SMALL SUBSET FIRST with-# `--region` (e.g. a few CA agencies) before attempting the whole world.+# WHAT CHANGED, AND WHY IT MATTERS. This script used to scrape `url` fields out of+# the registry. Most US state files reference feeds by `transitland-atlas-id` with+# no URL at all, so 38 of California's 49 sources were silently dropped. Its feed+# names were also positional (`us_ca_0`, `us_ca_1`, …), which meant a two-field+# manifest, which meant **no MOTIS stop ids** — and without those, live delays+# cannot be matched to a stop. `gtfs_ingest`'s `resolve_feeds` now does the atlas+# resolution `build_ca_transit.ps1` pioneered, and emits the three-field manifest+# `manifest.rs::parse_feed_spec` reads. #-# Feeds come from the Transitous registry-# (github.com/public-transport/transitous, `feeds/*.json`), which points at each-# agency's official GTFS `.zip` — the same open data behind the P10 online boards.+# THIS IS A HEAVY DATA JOB and a large step up from what it replaces: hundreds of+# feeds and many GB of downloads, against the 18.9 MB pack the `.url`-only scrape+# produced. **`--region` and `--max-feeds` are how you stage it** — California+# first, which is the known-good case, then a few regions, then the world. Run it+# in WSL / Linux with plenty of disk. #-# Requirements: bash, curl, unzip, cargo (to build gtfs_ingest). `jq` is used to-# parse feed JSON when present; otherwise a grep fallback extracts `.zip` URLs.+# THE DIVISION OF LABOUR: this script owns network I/O — the two registry+# tarballs, and every feed zip — and `resolve_feeds` owns the resolution. That is+# what keeps `gtfs_ingest` dependency-free, and it is why downloads are cached+# here rather than there.+#+# Downloads are CONTENT-ADDRESSED: a feed's zip is stored under the SHA-256 of its+# URL, so a re-run with a different `--region` or `--max-feeds` re-uses everything+# it already has instead of re-fetching by feed name. Feed names are not stable+# across registry updates; URLs are.+#+# Requirements: bash, curl, unzip, cargo, tar, and sha256sum (or shasum). # # Usage: #   ./build_world_transit.sh [options] # # Options:-#   --work DIR       Scratch dir for the registry + downloads + unzipped GTFS+#   --work DIR       Scratch dir for the registries + downloads + unzipped GTFS #                    (default: ./world_transit_work). Reused/resumable. #   --out DIR        Output dir for world.transit (+ .json)  (default: --work).-#   --region GLOB    Only use registry files matching this glob under feeds/-#                    (e.g. 'us*', 'de*'). Default '*' (the whole world).-#                    USE THIS for the CA/subset validation run.-#   --limit N        Cap the number of feeds processed (0 = no cap, default 0).-#   --manifest FILE  Skip the registry entirely; build straight from a manifest-#                    of `feed_name=gtfs_dir` lines (already-unzipped feeds).+#   --region GLOB    Only resolve registry files matching this glob under feeds/+#                    (e.g. 'us-ca', 'us-*', 'de-*'). Default '*' (the whole world).+#                    USE THIS to stage the build.+#   --max-feeds N    Cap the number of feeds (0 = no cap, default 0). Applied to a+#                    name-sorted list, so the cap takes a stable prefix.+#   --manifest FILE  Skip the registries entirely; build straight from a manifest+#                    of `name=dir[=motis_prefix]` lines (already-unzipped feeds). #   --jobs N         Parallel downloads (default 6).-#   --publish        After building, upload world.transit via publish_r2.sh.+#   --pack-name NAME Output pack name (default 'world' -> world.transit).+#   --resolve-only   Resolve and report the plan, then stop. Downloads nothing.+#   --refresh        Re-fetch the registry tarballs even if they are cached.+#   --publish        After building, upload the pack via publish_r2.sh. #   --dry-run        Print what would happen; download/build nothing. #   -h|--help        Show this help. # # Examples:-#   # CA-only validation subset (small), no publish:-#   ./build_world_transit.sh --region 'us*' --limit 8 --out /tmp/catransit+#   # California only, the known-good staging step:+#   ./build_world_transit.sh --region 'us-ca' --out /tmp/catransit+#+#   # See what the whole world would resolve to, without fetching a byte:+#   ./build_world_transit.sh --resolve-only # #   # Whole world, then publish: #   export R2_ENDPOINT=... R2_ACCESS_KEY_ID=... R2_SECRET_ACCESS_KEY=... #   ./build_world_transit.sh --work /data/transit --publish-#-# LIMITATION: this scrapes `url` fields out of the registry, but most US state-# files reference feeds by `transitland-atlas-id` with no URL at all (38 of-# California's 49 sources), so those agencies are silently dropped. Use-# `build_ca_transit.ps1`, which resolves those ids through transitland-atlas, for-# any region where that matters.  HERE="$(cd "$(dirname "$0")" && pwd)" INGEST_DIR="$HERE/gtfs_ingest"@@ -59,124 +76,139 @@ INGEST_DIR="$HERE/gtfs_ingest" WORK="./world_transit_work" OUT="" REGION="*"-LIMIT=0+MAX_FEEDS=0 MANIFEST="" JOBS=6+PACK_NAME="world"+RESOLVE_ONLY=0+REFRESH=0 PUBLISH=0 DRY_RUN=0-PACK_NAME="world"-REGISTRY_TARBALL="https://codeload.github.com/public-transport/transitous/tar.gz/refs/heads/main"++TRANSITOUS_TARBALL="https://codeload.github.com/public-transport/transitous/tar.gz/refs/heads/main"+ATLAS_TARBALL="https://codeload.github.com/transitland/transitland-atlas/tar.gz/refs/heads/main"  while [[ $# -gt 0 ]]; do     case "$1" in         --work) WORK="$2"; shift 2 ;;         --out) OUT="$2"; shift 2 ;;         --region) REGION="$2"; shift 2 ;;-        --limit) LIMIT="$2"; shift 2 ;;+        --max-feeds) MAX_FEEDS="$2"; shift 2 ;;         --manifest) MANIFEST="$2"; shift 2 ;;         --jobs) JOBS="$2"; shift 2 ;;+        --pack-name) PACK_NAME="$2"; shift 2 ;;+        --resolve-only) RESOLVE_ONLY=1; shift ;;+        --refresh) REFRESH=1; shift ;;         --publish) PUBLISH=1; shift ;;         --dry-run) DRY_RUN=1; shift ;;-        -h|--help) sed -n '3,60p' "$0" | sed 's/^# \?//'; exit 0 ;;+        -h|--help) sed -n '4,71p' "$0" | sed 's/^# \?//'; exit 0 ;;         *) echo "Unknown arg: $1" >&2; exit 1 ;;     esac done OUT="${OUT:-$WORK}" -mkdir -p "$WORK" "$OUT"-GTFS_ROOT="$WORK/gtfs"          # unzipped feeds: $GTFS_ROOT/<feed_name>/-mkdir -p "$GTFS_ROOT"-BUILD_MANIFEST="$WORK/feeds.manifest"- need() { command -v "$1" >/dev/null || { echo "ERROR: '$1' is required but not installed" >&2; exit 1; }; } need curl need unzip need cargo+need tar++sha256_of_string() {+    if command -v sha256sum >/dev/null; then+        printf '%s' "$1" | sha256sum | cut -d' ' -f1+    elif command -v shasum >/dev/null; then+        printf '%s' "$1" | shasum -a 256 | cut -d' ' -f1+    else+        echo "ERROR: need sha256sum or shasum for the download cache" >&2+        exit 1+    fi+}+export -f sha256_of_string++mkdir -p "$WORK" "$OUT"+GTFS_ROOT="$WORK/gtfs"          # unzipped feeds: $GTFS_ROOT/<feed_name>/+CACHE="$WORK/cache"             # content-addressed zips: $CACHE/<sha256 of url>.zip+mkdir -p "$GTFS_ROOT" "$CACHE"+BUILD_MANIFEST="$WORK/feeds.manifest"+PLAN="$WORK/plan.tsv" -# --- 1. Build the ingest tool (release) ---+# --- 1. Build the ingest tools (release) --- echo "=== building gtfs_ingest (release) ===" if [[ "$DRY_RUN" == "0" ]]; then     ( cd "$INGEST_DIR" && cargo build --release ) fi INGEST_BIN="$INGEST_DIR/target/release/gtfs_ingest"+RESOLVE_BIN="$INGEST_DIR/target/release/resolve_feeds" -# A feed name safe for filenames / the string pool (feed provenance on device).-sanitize() { echo "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]\+/_/g; s/^_//; s/_$//'; }--# --- 2. Gather (feed_name  zip_url) pairs, unless a manifest was supplied ---+# --- 2. Resolve the plan, unless a manifest was supplied --- if [[ -n "$MANIFEST" ]]; then-    echo "=== using supplied manifest $MANIFEST (skipping registry) ==="+    echo "=== using supplied manifest $MANIFEST (skipping the registries) ==="     cp "$MANIFEST" "$BUILD_MANIFEST" else-    REG_DIR="$WORK/transitous"-    if [[ ! -d "$REG_DIR/feeds" ]]; then-        echo "=== fetching Transitous registry ==="-        if [[ "$DRY_RUN" == "0" ]]; then-            mkdir -p "$REG_DIR"-            curl -fsSL "$REGISTRY_TARBALL" | tar -xz -C "$REG_DIR" --strip-components=1+    # Fetch a registry tarball and extract it. Network I/O belongs here, not in+    # resolve_feeds, which is what keeps gtfs_ingest dependency-free.+    get_registry() {+        local url="$1" dir="$2" label="$3"+        if [[ -d "$dir/feeds" && "$REFRESH" == "0" ]]; then+            echo "=== reusing $label at $dir ==="+            return         fi-    else-        echo "=== reusing registry at $REG_DIR ==="-    fi--    echo "=== extracting GTFS zip URLs (region: $REGION) ==="-    # Pull every URL field from the matching feed JSONs and keep the GTFS zips.-    extract_urls() {-        local f="$1"-        if command -v jq >/dev/null; then-            jq -r '[.. | objects | .url? // empty] | .[]' "$f" 2>/dev/null || true-        else-            grep -oE '"url"[[:space:]]*:[[:space:]]*"[^"]+"' "$f" | sed -E 's/.*"url"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/'+        echo "=== fetching $label ==="+        if [[ "$DRY_RUN" == "1" ]]; then+            echo "[dry-run] curl -fsSL $url | tar -xz -C $dir --strip-components=1"+            return         fi+        rm -rf "$dir"+        mkdir -p "$dir"+        curl -fsSL "$url" | tar -xz -C "$dir" --strip-components=1+        [[ -d "$dir/feeds" ]] || { echo "ERROR: $label has no feeds/ dir after extraction" >&2; exit 1; }     }+    REG_DIR="$WORK/transitous"+    ATLAS_DIR="$WORK/transitland-atlas"+    get_registry "$TRANSITOUS_TARBALL" "$REG_DIR" "Transitous registry"+    get_registry "$ATLAS_TARBALL" "$ATLAS_DIR" "transitland-atlas" -    : > "$WORK/urls.txt"-    shopt -s nullglob-    for f in "$REG_DIR"/feeds/$REGION.json; do-        base="$(basename "$f" .json)"-        i=0-        while IFS= read -r url; do-            [[ -z "$url" ]] && continue-            # Skip GTFS-realtime / non-static endpoints (these are .pb streams,-            # not schedule zips) — e.g. `...gtfs_rt?...&feed_type=trip`.-            case "$url" in-                *gtfs_rt*|*gtfsrt*|*realtime*|*feed_type=*|*.pb|*.pb\?*) continue ;;-            esac-            # Keep only static GTFS schedule feeds (zip, or a gtfs path).-            case "$url" in-                *.zip|*.zip\?*|*gtfs*|*GTFS*) : ;;-                *) continue ;;-            esac-            name="$(sanitize "${base}_${i}")"-            printf '%s\t%s\n' "$name" "$url" >> "$WORK/urls.txt"-            i=$((i+1))-        done < <(extract_urls "$f")-    done-    shopt -u nullglob--    total="$(wc -l < "$WORK/urls.txt" | tr -d ' ')"-    echo "found $total candidate GTFS feeds"-    if [[ "$LIMIT" -gt 0 ]]; then-        head -n "$LIMIT" "$WORK/urls.txt" > "$WORK/urls.trim.txt"-        mv "$WORK/urls.trim.txt" "$WORK/urls.txt"-        echo "limited to $LIMIT feeds"+    echo "=== resolving feeds (region: $REGION, max: $MAX_FEEDS) ==="+    RESOLVE_ARGS=(--registry "$REG_DIR" --atlas "$ATLAS_DIR" --out "$PLAN"+                  --region "$REGION" --report)+    [[ "$MAX_FEEDS" -gt 0 ]] && RESOLVE_ARGS+=(--max-feeds "$MAX_FEEDS")+    if [[ "$DRY_RUN" == "1" ]]; then+        echo "[dry-run] $RESOLVE_BIN ${RESOLVE_ARGS[*]}"+        echo "Done (dry run)."+        exit 0+    fi+    "$RESOLVE_BIN" "${RESOLVE_ARGS[@]}"++    if [[ "$RESOLVE_ONLY" == "1" ]]; then+        echo "=== --resolve-only: the plan is in $PLAN, nothing downloaded ==="+        exit 0     fi      # --- 3. Download + unzip each feed (parallel, resumable) ---     echo "=== downloading + unzipping feeds (jobs: $JOBS) ==="-    : > "$BUILD_MANIFEST"     fetch_one() {         local name="$1" url="$2"-        local zip="$WORK/zips/$name.zip"         local dir="$GTFS_ROOT/$name"-        mkdir -p "$WORK/zips"+        # Already unzipped: nothing to do, however the zip got here.         if [[ -f "$dir/stops.txt" ]]; then return 0; fi-        if ! curl -fsSL --retry 3 -o "$zip" "$url"; then-            echo "  WARN: download failed: $name ($url)" >&2; return 0-        fi-        # Guard against HTML error pages / redirects that aren't a real zip.-        if [[ "$(head -c 2 "$zip" 2>/dev/null)" != "PK" ]]; then-            echo "  WARN: not a GTFS zip (skipped): $name ($url)" >&2; rm -f "$zip"; return 0+        # Content-addressed on the URL, not the feed name: names shift when the+        # registry is updated, URLs do not, so this cache survives a re-resolve.+        local zip="$CACHE/$(sha256_of_string "$url").zip"+        if [[ ! -f "$zip" ]]; then+            if ! curl -fsSL --retry 3 -o "$zip.partial" "$url"; then+                echo "  WARN: download failed: $name ($url)" >&2+                rm -f "$zip.partial"+                return 0+            fi+            # Guard against HTML error pages / auth walls that are not a real zip.+            if [[ "$(head -c 2 "$zip.partial" 2>/dev/null)" != "PK" ]]; then+                echo "  WARN: not a GTFS zip, probably an auth wall (skipped): $name ($url)" >&2+                rm -f "$zip.partial"+                return 0+            fi+            # Renamed only once complete, so an interrupted run never leaves a+            # truncated zip that looks cached.+            mv "$zip.partial" "$zip"         fi         mkdir -p "$dir"         if ! unzip -oq "$zip" -d "$dir" 2>/dev/null; then@@ -187,51 +219,54 @@ else             local inner; inner="$(dirname "$(find "$dir" -name stops.txt | head -n1)" 2>/dev/null || true)"             if [[ -n "$inner" && "$inner" != "$dir" ]]; then mv "$inner"/* "$dir"/ 2>/dev/null || true; fi         fi-        rm -f "$zip"+        if [[ ! -f "$dir/stops.txt" ]]; then+            echo "  WARN: no stops.txt in the zip: $name" >&2; rm -rf "$dir"+        fi     }-    export -f fetch_one sanitize-    export WORK GTFS_ROOT+    export -f fetch_one+    export GTFS_ROOT CACHE -    if [[ "$DRY_RUN" == "0" ]]; then-        # xargs -P for parallelism; each line is "name<TAB>url".-        awk -F'\t' '{print $1"\t"$2}' "$WORK/urls.txt" \-            | xargs -P "$JOBS" -I{} bash -c 'line="{}"; name="${line%%$'"'"'\t'"'"'*}"; url="${line#*$'"'"'\t'"'"'}"; fetch_one "$name" "$url"'-    fi+    # `name<TAB>url<TAB>motis_prefix`; the prefix is not needed to download.+    awk -F'\t' 'NF>=2 {print $1"\t"$2}' "$PLAN" \+        | xargs -P "$JOBS" -I{} bash -c 'line="{}"; name="${line%%$'"'"'\t'"'"'*}"; url="${line#*$'"'"'\t'"'"'}"; fetch_one "$name" "$url"' -    # Build the ingest manifest from feeds that actually have stops.txt.+    # --- 4. Build the three-field manifest from the plan, not from disk ---+    # From the plan, so the MOTIS prefix survives -- it exists nowhere on disk --+    # and so a stale feed left over from an earlier --region is not picked up.     : > "$BUILD_MANIFEST"-    for d in "$GTFS_ROOT"/*/; do-        [[ -f "${d}stops.txt" ]] || continue-        n="$(basename "$d")"-        printf '%s=%s\n' "$n" "${d%/}" >> "$BUILD_MANIFEST"-    done+    while IFS=$'\t' read -r name url prefix; do+        [[ -n "$name" ]] || continue+        dir="$GTFS_ROOT/$name"+        [[ -f "$dir/stops.txt" ]] || continue+        printf '%s=%s=%s\n' "$name" "$dir" "$prefix" >> "$BUILD_MANIFEST"+    done < "$PLAN" fi  nfeeds="$(wc -l < "$BUILD_MANIFEST" | tr -d ' ')"-echo "=== $nfeeds feeds ready in $BUILD_MANIFEST ==="+planned="$( [[ -f "$PLAN" ]] && wc -l < "$PLAN" | tr -d ' ' || echo "$nfeeds" )"+echo "=== $nfeeds of $planned feed(s) usable, listed in $BUILD_MANIFEST ===" if [[ "$nfeeds" -eq 0 ]]; then     echo "ERROR: no usable feeds — nothing to build" >&2     exit 1 fi+# A MOTIS prefix is what lets a live delay be matched to a stop, so a manifest+# without them builds a pack that silently cannot do that.+withprefix="$(awk -F'=' 'NF>=3 && $3 != "" {n++} END {print n+0}' "$BUILD_MANIFEST")"+if [[ "$withprefix" -lt "$nfeeds" ]]; then+    echo "WARNING: $((nfeeds - withprefix)) feed(s) have no MOTIS prefix; their stops" >&2+    echo "         cannot be matched to live delays." >&2+fi -# --- 4. Merge into a single world.transit ---+# --- 5. Merge into a single pack --- echo "=== running gtfs_ingest merge -> $OUT/$PACK_NAME.transit ==="-if [[ "$DRY_RUN" == "1" ]]; then-    echo "[dry-run] $INGEST_BIN $OUT $PACK_NAME --manifest $BUILD_MANIFEST"-else-    "$INGEST_BIN" "$OUT" "$PACK_NAME" --manifest "$BUILD_MANIFEST"-    echo "--- size + section breakdown ($OUT/$PACK_NAME.transit.json) ---"-    cat "$OUT/$PACK_NAME.transit.json"-fi+"$INGEST_BIN" "$OUT" "$PACK_NAME" --manifest "$BUILD_MANIFEST"+echo "--- size + section breakdown ($OUT/$PACK_NAME.transit.json) ---"+cat "$OUT/$PACK_NAME.transit.json" -# --- 5. Publish (optional) ---+# --- 6. Publish (optional) --- if [[ "$PUBLISH" == "1" ]]; then     echo "=== publishing $PACK_NAME.transit to R2 ==="-    if [[ "$DRY_RUN" == "1" ]]; then-        echo "[dry-run] would run publish_r2.sh $OUT/$PACK_NAME.transit --key $PACK_NAME.transit"-    else-        "$HERE/publish_r2.sh" "$OUT/$PACK_NAME.transit" --key "$PACK_NAME.transit"-    fi+    "$HERE/publish_r2.sh" "$OUT/$PACK_NAME.transit" --key "$PACK_NAME.transit" fi  echo "Done."
scripts/maps/gtfs_ingest/Cargo.toml
diff --git a/scripts/maps/gtfs_ingest/Cargo.toml b/scripts/maps/gtfs_ingest/Cargo.tomlindex 269af95971..26bb819401 100644--- a/scripts/maps/gtfs_ingest/Cargo.toml+++ b/scripts/maps/gtfs_ingest/Cargo.toml@@ -26,6 +26,9 @@ path = "src/lib.rs" [[bin]] name = "transit_stops" path = "src/bin/transit_stops.rs"+[[bin]]+name = "resolve_feeds"+path = "src/bin/resolve_feeds.rs"  [dependencies] 
scripts/maps/gtfs_ingest/src/bin/resolve_feeds.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/resolve_feeds.rs b/scripts/maps/gtfs_ingest/src/bin/resolve_feeds.rsnew file mode 100644index 0000000000..aac6370196--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/bin/resolve_feeds.rs@@ -0,0 +1,295 @@+//! `resolve_feeds` — turn the Transitous registry plus transitland-atlas into a+//! download plan whose feeds can carry MOTIS stop ids.+//!+//! Usage:+//!   resolve_feeds --registry DIR --atlas DIR --out PLAN.tsv+//!                 [--region GLOB] [--max-feeds N] [--report]+//!+//! `--registry` is an extracted `public-transport/transitous` checkout (its+//! `feeds/*.json`); `--atlas` is an extracted `transitland/transitland-atlas`+//! (its `feeds/*.dmfr.json`). Both are **fetched by the shell**, not here: this+//! crate has no HTTP stack and no dependencies at all, which is what lets it build+//! and run offline.+//!+//! The plan is a TSV of `name<TAB>url<TAB>motis_prefix`, which+//! `build_world_transit.sh` downloads and then turns into the three-field manifest+//! `manifest.rs::parse_feed_spec` reads.+//!+//! `--region` and `--max-feeds` are not conveniences. Resolving every `feeds/*.json`+//! means hundreds of feeds and many GB of downloads, against today's 18.9 MB+//! `world.transit` built from `.url` fields alone. Stage it: California first+//! (known-good), then a few regions, then the world.++use std::path::{Path, PathBuf};+use std::process::ExitCode;++use gtfs_ingest::json;+use gtfs_ingest::registry::{self, Resolution};++fn main() -> ExitCode {+    let argv: Vec<String> = std::env::args().skip(1).collect();+    let mut registry_dir: Option<PathBuf> = None;+    let mut atlas_dir: Option<PathBuf> = None;+    let mut out: Option<PathBuf> = None;+    let mut region = "*".to_string();+    let mut max_feeds = 0usize;+    let mut report = false;++    let mut i = 0;+    while i < argv.len() {+        let value = || argv.get(i + 1).cloned();+        match argv[i].as_str() {+            "--registry" => {+                registry_dir = value().map(PathBuf::from);+                i += 2;+            }+            "--atlas" => {+                atlas_dir = value().map(PathBuf::from);+                i += 2;+            }+            "--out" => {+                out = value().map(PathBuf::from);+                i += 2;+            }+            "--region" => {+                match value() {+                    Some(v) => region = v,+                    None => return fail("--region needs a value"),+                }+                i += 2;+            }+            "--max-feeds" => {+                let Some(raw) = value() else {+                    return fail("--max-feeds needs a value");+                };+                let Ok(n) = raw.parse() else {+                    return fail(&format!("--max-feeds wants a number, got '{raw}'"));+                };+                max_feeds = n;+                i += 2;+            }+            "--report" => {+                report = true;+                i += 1;+            }+            "-h" | "--help" => {+                usage();+                return ExitCode::SUCCESS;+            }+            other => {+                eprintln!("resolve_feeds: unexpected argument '{other}'");+                usage();+                return ExitCode::from(2);+            }+        }+    }++    let (Some(registry_dir), Some(atlas_dir), Some(out)) = (registry_dir, atlas_dir, out) else {+        eprintln!("resolve_feeds: --registry, --atlas and --out are all required");+        usage();+        return ExitCode::from(2);+    };++    // --- index the atlas ---+    let atlas_files = match json_files(&atlas_dir.join("feeds"), "*") {+        Ok(f) => f,+        Err(e) => return fail(&e),+    };+    let mut atlas_docs = Vec::with_capacity(atlas_files.len());+    for path in &atlas_files {+        match read_json(path) {+            Ok(v) => atlas_docs.push(v),+            // One malformed atlas document must not sink the whole resolution: the+            // atlas is a third-party checkout of thousands of files.+            Err(e) => eprintln!("resolve_feeds: skipping {}: {e}", path.display()),+        }+    }+    let atlas = registry::index_atlas(&atlas_docs);+    eprintln!(+        "resolve_feeds: indexed {} atlas feed(s) from {} document(s)",+        atlas.len(),+        atlas_docs.len()+    );++    // --- resolve the matching region files ---+    let region_files = match json_files(&registry_dir.join("feeds"), &region) {+        Ok(f) => f,+        Err(e) => return fail(&e),+    };+    if region_files.is_empty() {+        return fail(&format!(+            "no registry file matches --region '{region}' under {}/feeds",+            registry_dir.display()+        ));+    }+    eprintln!(+        "resolve_feeds: {} registry file(s) match --region '{region}'",+        region_files.len()+    );++    let mut resolution = Resolution::default();+    for path in &region_files {+        let name = path+            .file_stem()+            .map(|s| s.to_string_lossy().into_owned())+            .unwrap_or_default();+        match read_json(path) {+            Ok(doc) => registry::resolve_region(&name, &doc, &atlas, &mut resolution),+            Err(e) => eprintln!("resolve_feeds: skipping {}: {e}", path.display()),+        }+    }++    let before = resolution.feeds.len();+    registry::dedup(&mut resolution.feeds);+    let deduped = before - resolution.feeds.len();+    // Sorted before the cap, so --max-feeds takes a stable prefix rather than+    // whichever feeds the filesystem happened to list first.+    resolution.feeds.sort_by(|a, b| a.name.cmp(&b.name));+    if max_feeds > 0 && resolution.feeds.len() > max_feeds {+        eprintln!(+            "resolve_feeds: capping {} feed(s) at --max-feeds {max_feeds}",+            resolution.feeds.len()+        );+        resolution.feeds.truncate(max_feeds);+    }++    eprintln!(+        "resolve_feeds: {} feed(s) from {} source(s); {} skipped, {} duplicate(s) dropped",+        resolution.feeds.len(),+        resolution.considered,+        resolution.skipped.len(),+        deduped+    );+    if report {+        for f in &resolution.feeds {+            eprintln!("  {:<28} via {:<50} {}", f.name, f.via, f.url);+        }+        for s in &resolution.skipped {+            eprintln!("  SKIP {:<24} {}", s.name, s.why);+        }+    }+    if resolution.feeds.is_empty() {+        eprintln!("resolve_feeds: nothing resolved -- refusing to write an empty plan");+        return ExitCode::FAILURE;+    }++    let mut text = String::new();+    for f in &resolution.feeds {+        text.push_str(&format!("{}\t{}\t{}\n", f.name, f.url, f.source));+    }+    if let Err(e) = std::fs::write(&out, text) {+        return fail(&format!("cannot write {}: {e}", out.display()));+    }+    eprintln!("resolve_feeds: wrote {}", out.display());+    ExitCode::SUCCESS+}++fn fail(msg: &str) -> ExitCode {+    eprintln!("resolve_feeds: {msg}");+    ExitCode::FAILURE+}++fn usage() {+    eprintln!("usage: resolve_feeds --registry DIR --atlas DIR --out PLAN.tsv");+    eprintln!("                     [--region GLOB] [--max-feeds N] [--report]");+}++fn read_json(path: &Path) -> Result<json::Json, String> {+    let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?;+    json::parse(&text)+}++/// `.json` files in `dir` whose stem matches `pattern`, sorted so a run is+/// reproducible whatever order the filesystem lists them in.+fn json_files(dir: &Path, pattern: &str) -> Result<Vec<PathBuf>, String> {+    let entries = std::fs::read_dir(dir)+        .map_err(|e| format!("cannot read {}: {e}", dir.display()))?;+    let mut out = Vec::new();+    for e in entries {+        let path = e.map_err(|e| e.to_string())?.path();+        if !path.is_file() {+            continue;+        }+        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {+            continue;+        };+        if !name.ends_with(".json") {+            continue;+        }+        // Match on the stem, so `--region us-ca` finds `us-ca.json` and+        // `--region 'us-*'` finds every US state. The atlas's `.dmfr.json` files+        // have a `.dmfr` stem suffix, which `*` covers.+        let stem = name.trim_end_matches(".json");+        if glob_match(pattern, stem) {+            out.push(path);+        }+    }+    out.sort();+    Ok(out)+}++/// Shell-style `*` and `?` matching, which is what `--region` promises.+///+/// Iterative with a backtrack point rather than recursive: a pattern of all stars+/// against a long name is a well-known way to make the naive recursion take+/// exponential time.+fn glob_match(pattern: &str, text: &str) -> bool {+    let p: Vec<char> = pattern.chars().collect();+    let t: Vec<char> = text.chars().collect();+    let (mut pi, mut ti) = (0usize, 0usize);+    let mut star: Option<(usize, usize)> = None;+    while ti < t.len() {+        if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) {+            pi += 1;+            ti += 1;+        } else if pi < p.len() && p[pi] == '*' {+            star = Some((pi, ti));+            pi += 1;+        } else if let Some((sp, st)) = star {+            // Backtrack: let the star consume one more character.+            pi = sp + 1;+            ti = st + 1;+            star = Some((sp, st + 1));+        } else {+            return false;+        }+    }+    while pi < p.len() && p[pi] == '*' {+        pi += 1;+    }+    pi == p.len()+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn glob_matches_the_forms_region_promises() {+        assert!(glob_match("*", "us-ca"));+        assert!(glob_match("us-ca", "us-ca"));+        assert!(glob_match("us-*", "us-ca"));+        assert!(glob_match("us-*", "us-ny"));+        assert!(!glob_match("us-*", "de-by"));+        assert!(glob_match("*-ca", "us-ca"));+        assert!(glob_match("us-??", "us-ca"));+        assert!(!glob_match("us-??", "us-cal"));+        assert!(glob_match("*ca*", "us-ca-extra"));+        assert!(!glob_match("us-ca", "us-cal"));+        // An atlas document's stem keeps its `.dmfr`.+        assert!(glob_match("*", "bayarea.dmfr"));+    }++    #[test]+    fn glob_handles_the_pathological_patterns_without_hanging() {+        // The case the naive recursion goes exponential on.+        let text = "a".repeat(40) + "b";+        assert!(!glob_match("*a*a*a*a*a*a*a*a*c", &text));+        assert!(glob_match("*a*a*a*a*a*a*a*a*b", &text));+        assert!(glob_match("**", "anything"));+        assert!(glob_match("*", ""));+        assert!(!glob_match("?", ""));+        assert!(glob_match("", ""));+        assert!(!glob_match("", "x"));+    }+}
scripts/maps/gtfs_ingest/src/json.rs
diff --git a/scripts/maps/gtfs_ingest/src/json.rs b/scripts/maps/gtfs_ingest/src/json.rsnew file mode 100644index 0000000000..441c434075--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/json.rs@@ -0,0 +1,380 @@+//! A minimal JSON reader, for the transit registries.+//!+//! `gtfs_ingest` has **zero** dependencies, which is what lets it build and resolve+//! offline on any box. The Transitous and transitland-atlas registries are JSON, so+//! reading them needs a parser; pulling in serde for two file formats would trade+//! that property away.+//!+//! Deliberately small, and enough for exactly this job:+//!+//! * Objects, arrays, strings, numbers, `true`/`false`/`null`.+//! * String escapes including `\uXXXX`, with surrogate pairs joined -- agency names+//!   in these registries are full Unicode.+//! * Numbers are kept as `f64`; nothing here reads one, but discarding them would+//!   make the parser reject documents it should accept.+//!+//! What it does not do: streaming, duplicate-key policy, or any error recovery. A+//! malformed registry is an error with a byte offset, not a partial parse.++use std::collections::BTreeMap;++#[derive(Debug, Clone, PartialEq)]+pub enum Json {+    Null,+    Bool(bool),+    Number(f64),+    String(String),+    Array(Vec<Json>),+    Object(BTreeMap<String, Json>),+}++impl Json {+    /// A member of an object, or `None` when this is not an object or the key is+    /// absent. Chains, so `v.get("urls").and_then(|u| u.get("static_current"))`+    /// reads the way the document does.+    pub fn get(&self, key: &str) -> Option<&Json> {+        match self {+            Json::Object(m) => m.get(key),+            _ => None,+        }+    }++    pub fn as_str(&self) -> Option<&str> {+        match self {+            Json::String(s) => Some(s.as_str()),+            _ => None,+        }+    }++    /// The elements of an array, or an empty slice. A registry field that is+    /// sometimes a single value and sometimes a list is common enough that callers+    /// should not have to branch.+    pub fn as_array(&self) -> &[Json] {+        match self {+            Json::Array(v) => v.as_slice(),+            _ => &[],+        }+    }++    /// Truthiness in the sense the registries use: present, and not `null`, `false`,+    /// an empty string, or an empty container.+    pub fn is_truthy(&self) -> bool {+        match self {+            Json::Null => false,+            Json::Bool(b) => *b,+            Json::Number(n) => *n != 0.0,+            Json::String(s) => !s.is_empty(),+            Json::Array(v) => !v.is_empty(),+            Json::Object(m) => !m.is_empty(),+        }+    }+}++pub fn parse(text: &str) -> Result<Json, String> {+    let b = text.as_bytes();+    let mut i = 0usize;+    let v = value(b, &mut i)?;+    skip_ws(b, &mut i);+    if i != b.len() {+        return Err(format!("trailing bytes at offset {i}"));+    }+    Ok(v)+}++fn skip_ws(b: &[u8], i: &mut usize) {+    while *i < b.len() && matches!(b[*i], b' ' | b'\t' | b'\n' | b'\r') {+        *i += 1;+    }+}++fn expect(b: &[u8], i: &mut usize, c: u8) -> Result<(), String> {+    skip_ws(b, i);+    if b.get(*i) != Some(&c) {+        return Err(format!(+            "expected '{}' at offset {i}, found {:?}",+            c as char,+            b.get(*i).map(|x| *x as char)+        ));+    }+    *i += 1;+    Ok(())+}++fn value(b: &[u8], i: &mut usize) -> Result<Json, String> {+    skip_ws(b, i);+    match b.get(*i) {+        None => Err(format!("unexpected end of input at offset {i}")),+        Some(b'{') => {+            *i += 1;+            let mut map = BTreeMap::new();+            skip_ws(b, i);+            if b.get(*i) == Some(&b'}') {+                *i += 1;+                return Ok(Json::Object(map));+            }+            loop {+                skip_ws(b, i);+                let key = string(b, i)?;+                expect(b, i, b':')?;+                map.insert(key, value(b, i)?);+                skip_ws(b, i);+                match b.get(*i) {+                    Some(b',') => *i += 1,+                    Some(b'}') => {+                        *i += 1;+                        return Ok(Json::Object(map));+                    }+                    other => {+                        return Err(format!(+                            "expected ',' or '}}' at offset {i}, found {:?}",+                            other.map(|x| *x as char)+                        ))+                    }+                }+            }+        }+        Some(b'[') => {+            *i += 1;+            let mut items = Vec::new();+            skip_ws(b, i);+            if b.get(*i) == Some(&b']') {+                *i += 1;+                return Ok(Json::Array(items));+            }+            loop {+                items.push(value(b, i)?);+                skip_ws(b, i);+                match b.get(*i) {+                    Some(b',') => *i += 1,+                    Some(b']') => {+                        *i += 1;+                        return Ok(Json::Array(items));+                    }+                    other => {+                        return Err(format!(+                            "expected ',' or ']' at offset {i}, found {:?}",+                            other.map(|x| *x as char)+                        ))+                    }+                }+            }+        }+        Some(b'"') => Ok(Json::String(string(b, i)?)),+        Some(b't') => literal(b, i, "true").map(|_| Json::Bool(true)),+        Some(b'f') => literal(b, i, "false").map(|_| Json::Bool(false)),+        Some(b'n') => literal(b, i, "null").map(|_| Json::Null),+        Some(_) => number(b, i),+    }+}++fn literal(b: &[u8], i: &mut usize, want: &str) -> Result<(), String> {+    if b[*i..].starts_with(want.as_bytes()) {+        *i += want.len();+        Ok(())+    } else {+        Err(format!("expected '{want}' at offset {i}"))+    }+}++fn number(b: &[u8], i: &mut usize) -> Result<Json, String> {+    let start = *i;+    while *i < b.len() && matches!(b[*i], b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E') {+        *i += 1;+    }+    if *i == start {+        return Err(format!("not a value at offset {start}"));+    }+    std::str::from_utf8(&b[start..*i])+        .ok()+        .and_then(|s| s.parse().ok())+        .map(Json::Number)+        .ok_or_else(|| format!("bad number at offset {start}"))+}++fn string(b: &[u8], i: &mut usize) -> Result<String, String> {+    expect(b, i, b'"')?;+    let mut out = String::new();+    loop {+        match b.get(*i) {+            None => return Err(format!("unterminated string at offset {i}")),+            Some(b'"') => {+                *i += 1;+                return Ok(out);+            }+            Some(b'\\') => {+                *i += 1;+                match b.get(*i) {+                    Some(b'"') => out.push('"'),+                    Some(b'\\') => out.push('\\'),+                    Some(b'/') => out.push('/'),+                    Some(b'b') => out.push('\u{8}'),+                    Some(b'f') => out.push('\u{c}'),+                    Some(b'n') => out.push('\n'),+                    Some(b'r') => out.push('\r'),+                    Some(b't') => out.push('\t'),+                    Some(b'u') => {+                        let hi = hex4(b, i)?;+                        // A high surrogate must be followed by its low half, or the+                        // agency name comes out as two replacement characters.+                        if (0xD800..0xDC00).contains(&hi) {+                            if b.get(*i + 1) == Some(&b'\\') && b.get(*i + 2) == Some(&b'u') {+                                *i += 2;+                                let lo = hex4(b, i)?;+                                if (0xDC00..0xE000).contains(&lo) {+                                    let c = 0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00);+                                    out.push(char::from_u32(c).unwrap_or('\u{fffd}'));+                                } else {+                                    out.push('\u{fffd}');+                                    out.push(char::from_u32(lo).unwrap_or('\u{fffd}'));+                                }+                            } else {+                                out.push('\u{fffd}');+                            }+                        } else {+                            out.push(char::from_u32(hi).unwrap_or('\u{fffd}'));+                        }+                    }+                    other => {+                        return Err(format!(+                            "bad escape at offset {i}: {:?}",+                            other.map(|x| *x as char)+                        ))+                    }+                }+                *i += 1;+            }+            Some(_) => {+                // Copy the whole UTF-8 run up to the next escape or quote in one go.+                let start = *i;+                while *i < b.len() && b[*i] != b'"' && b[*i] != b'\\' {+                    *i += 1;+                }+                out.push_str(+                    std::str::from_utf8(&b[start..*i])+                        .map_err(|_| format!("invalid UTF-8 at offset {start}"))?,+                );+            }+        }+    }+}++/// Read the four hex digits after a `\u`, leaving `i` on the last of them.+fn hex4(b: &[u8], i: &mut usize) -> Result<u32, String> {+    let start = *i + 1;+    let end = start + 4;+    if end > b.len() {+        return Err(format!("truncated \\u escape at offset {start}"));+    }+    let s = std::str::from_utf8(&b[start..end]).map_err(|_| format!("bad \\u at {start}"))?;+    let v = u32::from_str_radix(s, 16).map_err(|_| format!("bad \\u escape at offset {start}"))?;+    *i = end - 1;+    Ok(v)+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn reads_the_shapes_a_registry_uses() {+        let v = parse(+            r#"{"sources":[{"name":"SF-bayarea","transitland-atlas-id":"f-9q9-bayarea",+               "url":"https://example.com/gtfs.zip","skip":false,"spec":"gtfs"}]}"#,+        )+        .unwrap();+        let s = &v.get("sources").unwrap().as_array()[0];+        assert_eq!(s.get("name").unwrap().as_str(), Some("SF-bayarea"));+        assert_eq!(+            s.get("transitland-atlas-id").unwrap().as_str(),+            Some("f-9q9-bayarea")+        );+        assert!(!s.get("skip").unwrap().is_truthy());+        assert_eq!(v.get("nope"), None);+    }++    #[test]+    fn reads_a_nested_atlas_entry() {+        let v = parse(+            r#"{"feeds":[{"id":"f-9q9-bayarea","spec":"gtfs",+               "urls":{"static_current":"https://a/x.zip",+                       "static_historic":["https://a/old.zip","https://a/older.zip"]},+               "authorization":{"type":"query_param"}}]}"#,+        )+        .unwrap();+        let f = &v.get("feeds").unwrap().as_array()[0];+        let urls = f.get("urls").unwrap();+        assert_eq!(urls.get("static_current").unwrap().as_str(), Some("https://a/x.zip"));+        assert_eq!(urls.get("static_historic").unwrap().as_array().len(), 2);+        assert!(f.get("authorization").unwrap().is_truthy());+    }++    #[test]+    fn handles_escapes_and_unicode() {+        let v = parse(r#"{"a":"quote\" back\\ slash\/ nl\n tab\t","b":"\u00e9\u4e2d"}"#).unwrap();+        assert_eq!(+            v.get("a").unwrap().as_str(),+            Some("quote\" back\\ slash/ nl\n tab\t")+        );+        assert_eq!(v.get("b").unwrap().as_str(), Some("é中"));+    }++    #[test]+    fn joins_surrogate_pairs() {+        // An emoji in an agency name, which is not hypothetical.+        let v = parse(r#"{"a":"\ud83d\ude80"}"#).unwrap();+        assert_eq!(v.get("a").unwrap().as_str(), Some("🚀"));+        // A lone high surrogate becomes a replacement character rather than an error.+        let v = parse(r#"{"a":"\ud83dx"}"#).unwrap();+        assert_eq!(v.get("a").unwrap().as_str(), Some("\u{fffd}x"));+    }++    #[test]+    fn numbers_booleans_and_null_round_trip_enough_to_not_reject_a_document() {+        let v = parse(r#"{"a":1,"b":-2.5,"c":1e3,"d":true,"e":false,"f":null}"#).unwrap();+        assert_eq!(v.get("a"), Some(&Json::Number(1.0)));+        assert_eq!(v.get("b"), Some(&Json::Number(-2.5)));+        assert_eq!(v.get("c"), Some(&Json::Number(1000.0)));+        assert!(v.get("d").unwrap().is_truthy());+        assert!(!v.get("e").unwrap().is_truthy());+        assert!(!v.get("f").unwrap().is_truthy());+    }++    #[test]+    fn whitespace_and_empty_containers_are_fine() {+        assert_eq!(parse("  {  }  ").unwrap(), Json::Object(BTreeMap::new()));+        assert_eq!(parse("[ ]").unwrap(), Json::Array(vec![]));+        assert_eq!(+            parse("{\n\t\"a\" : [ 1 , 2 ]\n}").unwrap().get("a").unwrap().as_array().len(),+            2+        );+    }++    #[test]+    fn malformed_input_is_an_error_with_an_offset_not_a_partial_parse() {+        for bad in [+            "",+            "{",+            "{\"a\"}",+            "{\"a\":}",+            "{\"a\":1,}",+            "[1,]",+            "\"unterminated",+            "{\"a\":1} trailing",+            "tru",+            "{\"a\":\"\\q\"}",+            "{\"a\":\"\\u00\"}",+        ] {+            let err = parse(bad).unwrap_err();+            assert!(!err.is_empty(), "{bad:?} must report something");+        }+    }++    #[test]+    fn accessors_do_not_panic_on_the_wrong_shape() {+        let v = Json::String("x".into());+        assert_eq!(v.get("a"), None);+        assert!(v.as_array().is_empty());+        assert_eq!(Json::Null.as_str(), None);+        assert!(Json::Number(1.0).as_array().is_empty());+    }+}
scripts/maps/gtfs_ingest/src/lib.rs
diff --git a/scripts/maps/gtfs_ingest/src/lib.rs b/scripts/maps/gtfs_ingest/src/lib.rsindex a673b03289..15bd351c1e 100644--- a/scripts/maps/gtfs_ingest/src/lib.rs+++ b/scripts/maps/gtfs_ingest/src/lib.rs@@ -1,11 +1,17 @@ //! Shared GTFS ingest internals for the Maps offline packs. //! //! Exists so the crate can carry more than one host binary over the same GTFS-//! parser: `gtfs_ingest` builds the on-device `.transit` index, and-//! `transit_stops` emits the basemap stop layer. Mirrors `osm_ingest`'s-//! lib + `src/bin/*` shape.-+//! parser: `gtfs_ingest` builds the on-device `.transit` index, `transit_stops`+//! emits the basemap stop layer, and `resolve_feeds` turns the Transitous and+//! transitland-atlas registries into a download plan whose feeds can carry MOTIS+//! stop ids. Mirrors `osm_ingest`'s lib + `src/bin/*` shape.+//!+//! **Zero dependencies, deliberately.** That includes the JSON reader in [`json`]:+//! pulling in serde for two registry formats would trade away the property that+//! makes this crate build and run offline on any box. pub mod gtfs; pub mod index;+pub mod json; pub mod manifest;+pub mod registry; pub mod shapes;
scripts/maps/gtfs_ingest/src/registry.rs
diff --git a/scripts/maps/gtfs_ingest/src/registry.rs b/scripts/maps/gtfs_ingest/src/registry.rsnew file mode 100644index 0000000000..3833abbc47--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/registry.rs@@ -0,0 +1,479 @@+//! Resolving the Transitous registry against transitland-atlas, so a feed's stops+//! can carry MOTIS ids.+//!+//! A port of `build_ca_transit.ps1`'s resolution, generalised from one region file+//! to a glob over all of them. `build_world_transit.sh` used to scrape `url` fields+//! out of the registry, which silently dropped every source referenced only by+//! `transitland-atlas-id` -- **38 of California's 49**. Worse, index-based feed names+//! (`us_ca_0`, `us_ca_1`, …) meant its manifest was two-field, so nothing had a+//! MOTIS prefix and live delays could never be matched to a stop.+//!+//! # Why the atlas is consulted even when the registry has a URL+//!+//! An agency is usually listed **twice** in the atlas: once for its schedule+//! (`spec: gtfs`) and once for its realtime feed (`spec: gtfs-rt`). Only the atlas+//! entry's `spec` distinguishes them. If the registry's `url-override` were trusted+//! first, a realtime endpoint could win the dedup and knock the real schedule out of+//! the build -- a feed silently missing its timetable, which is worse than a feed+//! that is loudly absent. So the atlas entry is resolved and its `spec` checked+//! before any URL is chosen.+//!+//! # URL precedence+//!+//! 1. `url-override` from the registry -- a deliberate correction, so it wins.+//! 2. `url` from the registry.+//! 3. `urls.static_current` from the atlas, **unless** the feed has an+//!    `authorization` block, in which case an unauthenticated fetch will fail.+//! 4. The first `urls.static_historic` entry -- stale beats absent.+//! 5. `static_current` anyway, as a last resort, flagged as likely to fail.+//!+//! # Two names per feed, and why+//!+//! [`Resolved::name`] is sanitised for use as a directory and a string-pool entry;+//! [`Resolved::source`] is the registry's original name, which is what composes the+//! MOTIS prefix. `SF-bayarea` sanitises to `sf_bayarea` and cannot be recovered from+//! it, which is exactly why the two are carried separately and why the manifest has+//! three fields.++use crate::json::Json;++/// One usable feed.+#[derive(Debug, Clone, PartialEq)]+pub struct Resolved {+    /// Filename- and pool-safe. Also the manifest's first field.+    pub name: String,+    /// The registry's original source name, unmangled. Composes the MOTIS prefix.+    pub source: String,+    pub url: String,+    /// Which rule chose the URL, for the report.+    pub via: &'static str,+}++/// One source that could not be used, and why. Reported rather than dropped: a feed+/// vanishing without explanation is how 38 of California's agencies went missing for+/// as long as they did.+#[derive(Debug, Clone, PartialEq)]+pub struct Skipped {+    pub name: String,+    pub why: String,+}++#[derive(Debug, Default)]+pub struct Resolution {+    pub feeds: Vec<Resolved>,+    pub skipped: Vec<Skipped>,+    /// Sources seen across every region file.+    pub considered: usize,+}++/// `Get-SafeName`: lowercase, and every run of non-alphanumerics becomes one `_`.+pub fn safe_name(s: &str) -> String {+    let mut out = String::with_capacity(s.len());+    let mut pending = false;+    for c in s.chars() {+        if c.is_ascii_alphanumeric() {+            if pending && !out.is_empty() {+                out.push('_');+            }+            pending = false;+            out.push(c.to_ascii_lowercase());+        } else {+            pending = true;+        }+    }+    out+}++/// An index of every atlas feed by its id, built from the `*.dmfr.json` documents.+pub fn index_atlas(docs: &[Json]) -> std::collections::HashMap<&str, &Json> {+    let mut out = std::collections::HashMap::new();+    for doc in docs {+        for feed in doc.get("feeds").map(Json::as_array).unwrap_or_default() {+            if let Some(id) = feed.get("id").and_then(Json::as_str) {+                out.insert(id, feed);+            }+        }+    }+    out+}++/// A URL that is a realtime endpoint rather than a schedule zip.+///+/// Tests the **path**, not the whole URL, and treats a `.zip` as definitively+/// static. `build_world_transit.sh` matched `*realtime*` against the whole URL,+/// which threw away Golden Gate Transit's perfectly good schedule zip because it is+/// served from `realtime.goldengate.org`.+pub fn is_realtime(url: &str) -> bool {+    let path = url.split('?').next().unwrap_or(url);+    let lower = path.to_ascii_lowercase();+    if lower.ends_with(".zip") {+        return false;+    }+    lower.contains("gtfs-rt")+        || lower.contains("gtfs_rt")+        || lower.contains("gtfsrt")+        || lower.ends_with(".pb")+        || url.contains("feed_type=")+}++/// Resolve one registry region file's sources.+///+/// `region` is the file's base name (`us-ca`), which prefixes the MOTIS namespace.+pub fn resolve_region(+    region: &str,+    registry: &Json,+    atlas: &std::collections::HashMap<&str, &Json>,+    out: &mut Resolution,+) {+    for s in registry.get("sources").map(Json::as_array).unwrap_or_default() {+        out.considered += 1;+        let atlas_id = s.get("transitland-atlas-id").and_then(Json::as_str);+        let name = s+            .get("name")+            .and_then(Json::as_str)+            .or(atlas_id)+            .unwrap_or("")+            .to_string();+        let mut skip = |why: String| out.skipped.push(Skipped { name: name.clone(), why });++        if s.get("skip").is_some_and(Json::is_truthy) {+            let reason = s+                .get("skip-reason")+                .and_then(Json::as_str)+                .unwrap_or("no reason given");+            skip(format!("registry says skip: {reason}"));+            continue;+        }+        if let Some(spec) = s.get("spec").and_then(Json::as_str) {+            if spec != "gtfs" {+                skip(format!("registry spec is {spec}"));+                continue;+            }+        }+        if name.is_empty() {+            skip("source has neither a name nor an atlas id".to_string());+            continue;+        }++        // The atlas entry is resolved BEFORE any URL is chosen. See the module docs.+        let mut feed: Option<&Json> = None;+        if let Some(id) = atlas_id {+            match atlas.get(id) {+                None => {+                    skip(format!("atlas id {id} is not in the atlas"));+                    continue;+                }+                Some(f) => {+                    match f.get("spec").and_then(Json::as_str) {+                        // A missing spec means gtfs, which is the atlas default.+                        None | Some("gtfs") => feed = Some(f),+                        Some(other) => {+                            skip(format!("atlas spec is {other}"));+                            continue;+                        }+                    }+                }+            }+        }++        let needs_key = feed.is_some_and(|f| f.get("authorization").is_some_and(Json::is_truthy));+        let urls = feed.and_then(|f| f.get("urls"));+        let current = urls.and_then(|u| u.get("static_current")).and_then(Json::as_str);+        let historic = urls+            .and_then(|u| u.get("static_historic"))+            .map(Json::as_array)+            .unwrap_or_default()+            .iter()+            .filter_map(Json::as_str)+            .find(|u| !u.is_empty());++        let chosen: Option<(&str, &'static str)> = s+            .get("url-override")+            .and_then(Json::as_str)+            .filter(|u| !u.is_empty())+            .map(|u| (u, "url-override"))+            .or_else(|| {+                s.get("url")+                    .and_then(Json::as_str)+                    .filter(|u| !u.is_empty())+                    .map(|u| (u, "registry url"))+            })+            .or_else(|| {+                current+                    .filter(|u| !u.is_empty() && !needs_key)+                    .map(|u| (u, "atlas static_current"))+            })+            .or_else(|| {+                historic.map(|u| {+                    if needs_key {+                        (u, "atlas static_historic (static_current needs a key)")+                    } else {+                        (u, "atlas static_historic")+                    }+                })+            })+            .or_else(|| {+                current+                    .filter(|u| !u.is_empty())+                    .map(|u| (u, "atlas static_current (needs a key; will likely fail)"))+            });++        let Some((url, via)) = chosen else {+            skip("no usable GTFS URL".to_string());+            continue;+        };+        if is_realtime(url) {+            skip(format!("URL is a realtime endpoint: {url}"));+            continue;+        }++        out.feeds.push(Resolved {+            name: safe_name(&name),+            source: format!("{region}-{name}"),+            url: url.to_string(),+            via,+        });+    }+}++/// Drop duplicates, keeping the first of each name and then of each URL.+///+/// Two passes because they catch different things: the same agency listed in two+/// region files shares a name, and two differently-named sources pointing at one+/// combined feed share a URL. Both would otherwise be downloaded and merged twice.+pub fn dedup(feeds: &mut Vec<Resolved>) {+    let mut names = std::collections::HashSet::new();+    feeds.retain(|f| names.insert(f.name.clone()));+    let mut urls = std::collections::HashSet::new();+    feeds.retain(|f| urls.insert(f.url.clone()));+}++#[cfg(test)]+mod tests {+    use super::*;+    use crate::json;++    fn atlas_docs(text: &str) -> Vec<Json> {+        vec![json::parse(text).unwrap()]+    }++    fn resolve(region_text: &str, atlas_text: &str) -> Resolution {+        let docs = atlas_docs(atlas_text);+        let atlas = index_atlas(&docs);+        let registry = json::parse(region_text).unwrap();+        let mut out = Resolution::default();+        resolve_region("us-ca", &registry, &atlas, &mut out);+        out+    }++    const ATLAS: &str = r#"{"feeds":[+        {"id":"f-static","spec":"gtfs","urls":{"static_current":"https://a/sched.zip"}},+        {"id":"f-rt","spec":"gtfs-rt","urls":{"static_current":"https://a/rt.pb"}},+        {"id":"f-keyed","spec":"gtfs","authorization":{"type":"query_param"},+         "urls":{"static_current":"https://a/keyed.zip",+                 "static_historic":["https://a/old.zip"]}},+        {"id":"f-nospec","urls":{"static_current":"https://a/nospec.zip"}},+        {"id":"f-nourl","spec":"gtfs","urls":{}}+    ]}"#;++    #[test]+    fn safe_name_matches_get_safe_name() {+        assert_eq!(safe_name("SF-bayarea"), "sf_bayarea");+        assert_eq!(safe_name("Golden Gate Transit"), "golden_gate_transit");+        assert_eq!(safe_name("--leading and trailing--"), "leading_and_trailing");+        assert_eq!(safe_name("a...b"), "a_b");+        assert_eq!(safe_name("ALLCAPS"), "allcaps");+        assert_eq!(safe_name(""), "");+        assert_eq!(safe_name("---"), "");+    }++    #[test]+    fn a_source_referenced_only_by_atlas_id_resolves() {+        // The whole point: build_world_transit.sh dropped these, 38 of 49 in CA.+        let r = resolve(r#"{"sources":[{"transitland-atlas-id":"f-static"}]}"#, ATLAS);+        assert_eq!(r.feeds.len(), 1, "{:?}", r.skipped);+        assert_eq!(r.feeds[0].url, "https://a/sched.zip");+        assert_eq!(r.feeds[0].via, "atlas static_current");+        // The name falls back to the atlas id when the registry gives none.+        assert_eq!(r.feeds[0].name, "f_static");+        assert_eq!(r.feeds[0].source, "us-ca-f-static");+    }++    #[test]+    fn the_motis_prefix_keeps_the_unmangled_source_name() {+        let r = resolve(+            r#"{"sources":[{"name":"SF-bayarea","transitland-atlas-id":"f-static"}]}"#,+            ATLAS,+        );+        // Sanitising is lossy, which is why both names are carried.+        assert_eq!(r.feeds[0].name, "sf_bayarea");+        assert_eq!(r.feeds[0].source, "us-ca-SF-bayarea");+    }++    #[test]+    fn url_precedence_runs_override_registry_current_historic() {+        let r = resolve(+            r#"{"sources":[{"name":"A","transitland-atlas-id":"f-static",+                 "url-override":"https://o/x.zip","url":"https://r/x.zip"}]}"#,+            ATLAS,+        );+        assert_eq!(r.feeds[0].url, "https://o/x.zip");+        assert_eq!(r.feeds[0].via, "url-override");++        let r = resolve(+            r#"{"sources":[{"name":"A","transitland-atlas-id":"f-static","url":"https://r/x.zip"}]}"#,+            ATLAS,+        );+        assert_eq!(r.feeds[0].url, "https://r/x.zip");+        assert_eq!(r.feeds[0].via, "registry url");+    }++    #[test]+    fn an_authorized_feed_prefers_a_historic_url_over_one_needing_a_key() {+        // static_current would 401. Stale beats absent.+        let r = resolve(r#"{"sources":[{"name":"K","transitland-atlas-id":"f-keyed"}]}"#, ATLAS);+        assert_eq!(r.feeds[0].url, "https://a/old.zip");+        assert_eq!(r.feeds[0].via, "atlas static_historic (static_current needs a key)");+    }++    #[test]+    fn a_keyed_feed_with_no_history_falls_back_and_says_so() {+        let atlas = atlas_docs(+            r#"{"feeds":[{"id":"f-k","spec":"gtfs","authorization":{"type":"header"},+                 "urls":{"static_current":"https://a/keyed.zip"}}]}"#,+        );+        let index = index_atlas(&atlas);+        let mut out = Resolution::default();+        resolve_region(+            "us-ca",+            &json::parse(r#"{"sources":[{"name":"K","transitland-atlas-id":"f-k"}]}"#).unwrap(),+            &index,+            &mut out,+        );+        assert_eq!(out.feeds[0].url, "https://a/keyed.zip");+        assert!(out.feeds[0].via.contains("will likely fail"));+    }++    #[test]+    fn the_atlas_spec_is_checked_before_any_url_is_chosen() {+        // A realtime atlas entry is refused even though the registry supplies a+        // perfectly fetchable override. Trusting the override first is how a+        // realtime endpoint wins the dedup and knocks out the real schedule.+        let r = resolve(+            r#"{"sources":[{"name":"RT","transitland-atlas-id":"f-rt",+                 "url-override":"https://o/looks-fine.zip"}]}"#,+            ATLAS,+        );+        assert!(r.feeds.is_empty(), "{:?}", r.feeds);+        assert_eq!(r.skipped.len(), 1);+        assert!(r.skipped[0].why.contains("atlas spec is gtfs-rt"), "{:?}", r.skipped);+    }++    #[test]+    fn a_missing_atlas_spec_counts_as_gtfs() {+        let r = resolve(r#"{"sources":[{"name":"N","transitland-atlas-id":"f-nospec"}]}"#, ATLAS);+        assert_eq!(r.feeds.len(), 1, "{:?}", r.skipped);+        assert_eq!(r.feeds[0].url, "https://a/nospec.zip");+    }++    #[test]+    fn every_skip_reason_is_reported_rather_than_silent() {+        let cases = [+            (+                r#"{"sources":[{"name":"S","skip":true,"skip-reason":"broken since 2019"}]}"#,+                "registry says skip: broken since 2019",+            ),+            (+                r#"{"sources":[{"name":"S","spec":"gtfs-rt","url":"https://a/x.zip"}]}"#,+                "registry spec is gtfs-rt",+            ),+            (+                r#"{"sources":[{"name":"S","transitland-atlas-id":"f-missing"}]}"#,+                "atlas id f-missing is not in the atlas",+            ),+            (+                r#"{"sources":[{"name":"S","transitland-atlas-id":"f-nourl"}]}"#,+                "no usable GTFS URL",+            ),+            (r#"{"sources":[{"name":"S"}]}"#, "no usable GTFS URL"),+            (r#"{"sources":[{"url":"https://a/x.zip"}]}"#, "neither a name nor an atlas id"),+        ];+        for (text, want) in cases {+            let r = resolve(text, ATLAS);+            assert!(r.feeds.is_empty(), "{text} should not resolve");+            assert_eq!(r.skipped.len(), 1, "{text}");+            assert!(+                r.skipped[0].why.contains(want),+                "{text}: wanted {want:?}, got {:?}",+                r.skipped[0].why+            );+        }+    }++    #[test]+    fn realtime_detection_looks_at_the_path_and_spares_zips() {+        // The Golden Gate case: a schedule zip on a host called `realtime`.+        assert!(!is_realtime("https://realtime.goldengate.org/gtfs/sched.zip"));+        assert!(!is_realtime("https://a/gtfs.zip?key=1"));+        // Genuine realtime endpoints.+        assert!(is_realtime("https://a/gtfs-rt/trips"));+        assert!(is_realtime("https://a/gtfs_rt?agency=x"));+        assert!(is_realtime("https://a/gtfsrt/vehicles"));+        assert!(is_realtime("https://a/feed.pb"));+        assert!(is_realtime("https://a/api/feed?feed_type=trip"));+        // A query string alone does not make it realtime.+        assert!(!is_realtime("https://a/download?agency=x"));+    }++    #[test]+    fn a_realtime_url_is_skipped_even_when_the_atlas_says_gtfs() {+        let r = resolve(+            r#"{"sources":[{"name":"R","transitland-atlas-id":"f-static",+                 "url-override":"https://a/gtfs-rt/trips"}]}"#,+            ATLAS,+        );+        assert!(r.feeds.is_empty());+        assert!(r.skipped[0].why.contains("realtime endpoint"));+    }++    #[test]+    fn dedup_drops_repeats_by_name_then_by_url() {+        let mut feeds = vec![+            Resolved { name: "a".into(), source: "r-A".into(), url: "u1".into(), via: "x" },+            // Same name from another region file.+            Resolved { name: "a".into(), source: "s-A".into(), url: "u2".into(), via: "x" },+            // Different name, same combined feed.+            Resolved { name: "b".into(), source: "r-B".into(), url: "u1".into(), via: "x" },+            Resolved { name: "c".into(), source: "r-C".into(), url: "u3".into(), via: "x" },+        ];+        dedup(&mut feeds);+        assert_eq!(+            feeds.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(),+            ["a", "c"]+        );+        // The first of each is the one kept, so the result is order-stable.+        assert_eq!(feeds[0].source, "r-A");+    }++    #[test]+    fn a_registry_with_no_sources_resolves_to_nothing_without_erroring() {+        let r = resolve("{}", ATLAS);+        assert_eq!(r.considered, 0);+        assert!(r.feeds.is_empty() && r.skipped.is_empty());+        let r = resolve(r#"{"sources":[]}"#, ATLAS);+        assert_eq!(r.considered, 0);+    }++    #[test]+    fn the_atlas_index_covers_every_document() {+        let docs = vec![+            json::parse(r#"{"feeds":[{"id":"a"},{"id":"b"}]}"#).unwrap(),+            json::parse(r#"{"feeds":[{"id":"c"}]}"#).unwrap(),+            // A document with no feeds must not break the index.+            json::parse(r#"{"license":{}}"#).unwrap(),+        ];+        let index = index_atlas(&docs);+        assert_eq!(index.len(), 3);+        assert!(index.contains_key("a") && index.contains_key("c"));+    }+}