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

Modern-Apps.git / scripts / maps / build_world_transit.sh

build_world_transit.sh317 lines · 13.4 KiBRaw
1#!/bin/bash
2set -euo pipefail
3
4# build_world_transit.sh — build the single global offline transit index
5# (`world.transit`) by mirroring Transitous' own published GTFS directory and
6# merging every zip into one TRX2 pack via `scripts/maps/gtfs_ingest`.
7#
8# This mirrors the "single global graph" decision for roads: the app downloads ONE
9# transit pack on first open (see MainActivity's InitialDownloadChecker) and
10# `OfflineRouter` just iterates `*.transit` — no per-zone logic.
11#
12# ONE HOST, ONE MIRROR. Every feed comes from https://api.transitous.org/gtfs/,
13# which is Transitous' own already-fetched, already-normalised output. Nothing here
14# talks to an agency, a national access point, or a rehosting site.
15#
16# That replaced resolving the Transitous registry against transitland-atlas and then
17# fetching each feed from its upstream URL. Those upstreams are third parties in
18# every state of disrepair: 401s from WMATA and the Spanish NAP, 403s, 404s from
19# dead rehosts, hostname-mismatched TLS certs, broken pipes. Every one of them was a
20# warning to be read and ignored, and a feed silently missing from the pack.
21# Transitous already solves that problem — including the API keys we do not have —
22# so the fix is to take its output instead of repeating its work badly.
23#
24# THE FEED ID. A zip is `<region>_<Source>.gtfs.zip` and its MOTIS feed id is
25# `<region>-<Source>` — the same string `resolve_feeds` used to compose, and the
26# same one Transitous names its `scripts/*.lua` transforms after
27# (`au-vic_Transport-Victoria-metro-trains.gtfs.zip` <-> `au-vic-Transport-Victoria-
28# metro-trains.lua`). Only the FIRST underscore is a separator; the rest of the name
29# keeps its own hyphens and its case. Without that id the pack carries no MOTIS stop
30# ids and live delays cannot be matched to a stop.
31#
32# THIS IS A HEAVY DATA JOB: ~2250 feeds and ~10 GB mirrored. **`--region` is how you
33# stage it** — California first, which is the known-good case, then the world. Run it
34# in WSL / Linux with plenty of disk. The mirror is timestamp-based, so a re-run
35# re-fetches only what changed upstream.
36#
37# Requirements: bash, wget, unzip, cargo, and sha256sum (or shasum).
38#
39# Usage:
40# ./build_world_transit.sh
41#
42# No options. Work/out dirs are fixed:
43# <script-dir>/world_transit_work (mirror + unzipped GTFS + feeds.manifest)
44# <script-dir>/inputs/world.transit (+ .json, the pack)
45#
46# Examples:
47# ./build_world_transit.sh
48
49HERE="$(cd "$(dirname "$0")" && pwd)"
50INGEST_DIR="$HERE/gtfs_ingest"
51
52WORK="$HERE/world_transit_work"
53OUT="$HERE/inputs"
54REGION="*"
55MAX_FEEDS=0
56MANIFEST=""
57# How many feeds to unzip at once.
58#
59# The unzip loop only; the wget mirror below stays strictly serial on purpose --
60# see its own comment. Unzipping is CPU-bound (inflate) and touches only per-feed
61# directories, so this is the one place in this script that fans out safely.
62JOBS="${MAPS_JOBS:-4}"
63MIRROR_DIR="$WORK/transitous"
64SKIP_MIRROR=0
65RATE="30m"
66PACK_NAME="world"
67LIST_ONLY=0
68PUBLISH=0
69DRY_RUN=0
70
71# Transitous' published output: the zips it has already fetched and normalised,
72# plus the `scripts/` transforms that name each feed's MOTIS id.
73GTFS_INDEX_URL="https://api.transitous.org/gtfs/"
74
75# Fixed paths -- no options.
76
77need() { command -v "$1" >/dev/null || { echo "ERROR: '$1' is required but not installed" >&2; exit 1; }; }
78need unzip
79need cargo
80# Only when this run will actually fetch: a --dry-run, a supplied manifest or an
81# existing mirror all get by without it.
82[[ "$SKIP_MIRROR" == "1" || "$DRY_RUN" == "1" || -n "$MANIFEST" ]] || need wget
83
84mkdir -p "$WORK" "$OUT"
85GTFS_ROOT="$WORK/gtfs" # unzipped feeds: $GTFS_ROOT/<feed_name>/
86mkdir -p "$GTFS_ROOT"
87BUILD_MANIFEST="$WORK/feeds.manifest"
88
89# Delete a failed feed's unzip directory, and refuse to delete anything else.
90#
91# Every recursive delete in this script goes through here. It exists because the
92# flatten step below once computed a path of `.` and handed the repo root to a
93# plain `rm -rf`: a guard that asserts the target is a real subdirectory of
94# GTFS_ROOT turns that class of mistake into a refusal instead of data loss.
95discard_feed_dir() {
96 local target="$1" root
97 root="$(cd "$GTFS_ROOT" 2>/dev/null && pwd -P)" || return 0
98 [[ -n "$target" && -d "$target" ]] || return 0
99 target="$(cd "$target" 2>/dev/null && pwd -P)" || return 0
100 # Must be strictly inside GTFS_ROOT: not the root, not a parent, not elsewhere.
101 if [[ "$target" == "$root"/?* ]]; then
102 rm -rf "$target"
103 else
104 echo " REFUSED to delete '$target': not inside $root" >&2
105 fi
106}
107
108# `Get-SafeName`, matching gtfs_ingest's registry::safe_name: lowercase, and every
109# run of non-alphanumerics becomes one `_`. Used for the unzip directory only.
110safe_name() {
111 printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/_/g; s/^_+//; s/_+$//'
112}
113
114# --- 1. Build the ingest tool (release) ---
115echo "=== building gtfs_ingest (release) ==="
116if [[ "$DRY_RUN" == "0" ]]; then
117 ( cd "$INGEST_DIR" && cargo build --release )
118fi
119INGEST_BIN="$INGEST_DIR/target/release/gtfs_ingest"
120
121# --- 2. Mirror Transitous' published GTFS directory ---
122if [[ -n "$MANIFEST" ]]; then
123 echo "=== using supplied manifest $MANIFEST (skipping the mirror) ==="
124 cp "$MANIFEST" "$BUILD_MANIFEST"
125else
126 if [[ "$SKIP_MIRROR" == "1" ]]; then
127 echo "=== --skip-mirror: using the existing mirror at $MIRROR_DIR ==="
128 else
129 echo "=== mirroring $GTFS_INDEX_URL -> $MIRROR_DIR (rate: $RATE) ==="
130 mkdir -p "$MIRROR_DIR"
131 # ONE host, ONE recursive fetch. --mirror is timestamp-based, so a re-run
132 # only pulls what changed upstream. The `scripts/` transforms come along
133 # because they name each feed's MOTIS id, which is worth having on disk
134 # next to the zips it identifies.
135 #
136 # DO NOT fan this out. `--limit-rate` is per-process, so N parallel wgets
137 # silently multiply the load on a volunteer host by N -- the rate limit
138 # would still read 30m in the arguments while the host saw N x 30m. The
139 # unzip loop below is where this script gets its concurrency; overlap the
140 # download with CPU work instead of splitting the download.
141 MIRROR_ARGS=(
142 --limit-rate="$RATE" --mirror -l 2 --no-parent
143 --cut-dirs=1 --no-host-directories
144 --include-directories=gtfs,gtfs/scripts
145 --accept '.zip' --accept '.lua' --accept 'config.yml'
146 -e robots=off
147 -P "$MIRROR_DIR"
148 "$GTFS_INDEX_URL"
149 )
150 if [[ "$DRY_RUN" == "1" ]]; then
151 echo "[dry-run] wget ${MIRROR_ARGS[*]}"
152 else
153 # wget exits 8 on a server error for any single file. With ~2250 files
154 # one 404 must not fail the whole build, so the exit code is reported
155 # and the feed count below is what actually gates the build.
156 wget "${MIRROR_ARGS[@]}" || echo " NOTE: wget exited $? (partial mirror is expected; see the feed count)" >&2
157 fi
158 fi
159
160 # --- 3. Enumerate, filter, unzip ---
161 mapfile -t ZIPS < <(find "$MIRROR_DIR" -name '*.gtfs.zip' -type f 2>/dev/null | sort)
162 if [[ "$DRY_RUN" == "1" && "${#ZIPS[@]}" -eq 0 ]]; then
163 echo "[dry-run] no mirror on disk yet; nothing to enumerate"
164 echo "Done (dry run)."
165 exit 0
166 fi
167 echo "=== ${#ZIPS[@]} zip(s) in the mirror; region filter: $REGION ==="
168
169 : > "$BUILD_MANIFEST"
170
171 # --- 3a. Select, serially, in sorted order -------------------------------
172 #
173 # Cheap (name parsing and a glob match, no I/O), and it has to be serial anyway
174 # because `--max-feeds` contractually takes a stable prefix of the name-sorted
175 # list. Unzipping is the expensive part and happens below.
176 CAND_NAME=(); CAND_DIR=(); CAND_PREFIX=(); CAND_ZIP=()
177 for zip in ${ZIPS[@]+"${ZIPS[@]}"}; do
178 stem="$(basename "$zip" .gtfs.zip)"
179 # `<region>_<Source>`: only the FIRST underscore separates them, and the
180 # MOTIS id rejoins them with a hyphen. Everything after keeps its own
181 # hyphens and its case -- `us-ca_SF-bayarea` -> `us-ca-SF-bayarea`.
182 region="${stem%%_*}"
183 source_name="${stem#*_}"
184 [[ "$source_name" != "$stem" ]] || source_name=""
185 # shellcheck disable=SC2254 # REGION is a glob on purpose
186 case "$region" in
187 $REGION) : ;;
188 *) continue ;;
189 esac
190 if [[ -z "$source_name" ]]; then
191 echo " WARN: '$stem' has no <region>_<source> split; skipped" >&2
192 continue
193 fi
194 CAND_NAME+=("$(safe_name "$stem")")
195 CAND_PREFIX+=("$region-$source_name")
196 CAND_ZIP+=("$zip")
197 CAND_DIR+=("$GTFS_ROOT/$(safe_name "$stem")")
198 done
199 NCAND="${#CAND_NAME[@]}"
200
201 if [[ "$LIST_ONLY" == "1" ]]; then
202 used=0
203 for ((i = 0; i < NCAND; i++)); do
204 [[ "$MAX_FEEDS" -gt 0 && "$used" -ge "$MAX_FEEDS" ]] && break
205 printf '%s\t%s\t%s\n' "${CAND_NAME[$i]}" "${CAND_PREFIX[$i]}" "${CAND_ZIP[$i]}"
206 used=$((used + 1))
207 done
208 echo "=== --list-only: $used feed(s) would be used ==="
209 exit 0
210 fi
211
212 # --- 3b. Unzip, in parallel, in waves ------------------------------------
213 #
214 # Embarrassingly parallel: each feed is its own zip and its own directory. Two
215 # things constrain how:
216 #
217 # * The manifest must stay in sorted order, so each feed writes its line to
218 # its OWN fragment file and the fragments are concatenated by index. A
219 # shared append would interleave and make the order completion order.
220 # * `--max-feeds` counts feeds that actually unzipped, not feeds attempted, so
221 # the work goes out in waves and the count is checked between them. Selecting
222 # N candidates up front instead would silently return fewer than N whenever a
223 # zip was corrupt.
224 #
225 # A feed that fails is a warning, not a failure: one bad zip out of hundreds must
226 # not lose the build. Failure is signalled by an ABSENT fragment rather than an
227 # exit code, so the reap loop needs no error plumbing.
228 FRAG_DIR="$WORK/frag"
229 rm -rf "$FRAG_DIR"
230 mkdir -p "$FRAG_DIR"
231
232 unzip_feed() {
233 local i="$1"
234 local zip="${CAND_ZIP[$i]}" dir="${CAND_DIR[$i]}"
235 local name="${CAND_NAME[$i]}" prefix="${CAND_PREFIX[$i]}"
236 local stem
237 stem="$(basename "$zip" .gtfs.zip)"
238 if [[ ! -f "$dir/stops.txt" ]]; then
239 mkdir -p "$dir"
240 if ! unzip -oq "$zip" -d "$dir" 2>/dev/null; then
241 echo " WARN: unzip failed: $stem" >&2
242 discard_feed_dir "$dir"
243 return 0
244 fi
245 # Some feeds nest the txt files one dir deep; flatten if needed.
246 if [[ ! -f "$dir/stops.txt" ]]; then
247 local found inner
248 found="$(find "$dir" -name stops.txt 2>/dev/null | head -n1)"
249 # Test the find RESULT, not the dirname of it. `dirname ""` is `.`,
250 # so a zip with no stops.txt anywhere used to set inner="." and run
251 # `mv ./* "$dir"/` -- moving the whole current working directory
252 # into the feed dir, which the discard below then deleted.
253 if [[ -n "$found" ]]; then
254 inner="$(dirname "$found")"
255 if [[ "$inner" != "$dir" ]]; then
256 mv "$inner"/* "$dir"/ 2>/dev/null || true
257 fi
258 fi
259 fi
260 if [[ ! -f "$dir/stops.txt" ]]; then
261 echo " WARN: no stops.txt in the zip: $stem" >&2
262 discard_feed_dir "$dir"
263 return 0
264 fi
265 fi
266 printf '%s=%s=%s\n' "$name" "$dir" "$prefix" > "$FRAG_DIR/$i.line"
267 return 0
268 }
269
270 used=0
271 next=0
272 while [[ "$next" -lt "$NCAND" ]]; do
273 [[ "$MAX_FEEDS" -gt 0 && "$used" -ge "$MAX_FEEDS" ]] && break
274 wave_pids=(); wave_idx=()
275 while [[ "${#wave_pids[@]}" -lt "$JOBS" && "$next" -lt "$NCAND" ]]; do
276 unzip_feed "$next" &
277 wave_pids+=("$!")
278 wave_idx+=("$next")
279 next=$((next + 1))
280 done
281 for p in ${wave_pids[@]+"${wave_pids[@]}"}; do
282 wait "$p" || true
283 done
284 # In index order, so the manifest stays sorted however the wave finished.
285 for i in ${wave_idx[@]+"${wave_idx[@]}"}; do
286 [[ "$MAX_FEEDS" -gt 0 && "$used" -ge "$MAX_FEEDS" ]] && break
287 if [[ -s "$FRAG_DIR/$i.line" ]]; then
288 cat "$FRAG_DIR/$i.line" >> "$BUILD_MANIFEST"
289 used=$((used + 1))
290 fi
291 done
292 echo " ...$used feed(s) unzipped of $NCAND candidate(s)"
293 done
294 rm -rf "$FRAG_DIR"
295fi
296
297nfeeds="$(wc -l < "$BUILD_MANIFEST" | tr -d ' ')"
298echo "=== $nfeeds feed(s) usable, listed in $BUILD_MANIFEST ==="
299if [[ "$nfeeds" -eq 0 ]]; then
300 echo "ERROR: no usable feeds — nothing to build" >&2
301 exit 1
302fi
303# A MOTIS prefix is what lets a live delay be matched to a stop, so a manifest
304# without them builds a pack that silently cannot do that.
305withprefix="$(awk -F'=' 'NF>=3 && $3 != "" {n++} END {print n+0}' "$BUILD_MANIFEST")"
306if [[ "$withprefix" -lt "$nfeeds" ]]; then
307 echo "WARNING: $((nfeeds - withprefix)) feed(s) have no MOTIS prefix; their stops" >&2
308 echo " cannot be matched to live delays." >&2
309fi
310
311# --- 4. Merge into a single pack ---
312echo "=== running gtfs_ingest merge -> $OUT/$PACK_NAME.transit ==="
313"$INGEST_BIN" "$OUT" "$PACK_NAME" --manifest "$BUILD_MANIFEST"
314echo "--- size + section breakdown ($OUT/$PACK_NAME.transit.json) ---"
315cat "$OUT/$PACK_NAME.transit.json"
316
317echo "Done."