Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / gtfs_ingest / src / main.rs
main.rs376 lines · 15.9 KiBRaw
| 1 | //! `gtfs_ingest` — host build tool (P11a / world pack) that turns one or more |
| 2 | //! GTFS feeds into a single compact on-device transit index (`<pack>.transit`) |
| 3 | //! plus a small JSON manifest describing it, for the Maps offline packs. |
| 4 | //! |
| 5 | //! Usage: |
| 6 | //! gtfs_ingest <out_dir> <pack_name> <feed>... # feeds inline |
| 7 | //! gtfs_ingest <out_dir> <pack_name> --manifest <file> # feeds from a file |
| 8 | //! |
| 9 | //! Each `<feed>` is either `feed_name=gtfs_dir` or just `gtfs_dir` (the feed name |
| 10 | //! is then the directory's base name). An optional third field, |
| 11 | //! `feed_name=gtfs_dir=motis_prefix`, gives the feed's Transitous id namespace |
| 12 | //! (e.g. `us-ca-SF-bayarea`) so the pack can carry MOTIS stop ids; without it the |
| 13 | //! device simply reports none. A manifest file lists one such spec per line |
| 14 | //! (blank lines and `#` comments allowed). `gtfs_dir` is an UNZIPPED |
| 15 | //! GTFS feed directory (containing `stops.txt`, `routes.txt`, `trips.txt`, |
| 16 | //! `stop_times.txt`, and optionally `agency.txt` / `calendar.txt` / |
| 17 | //! `calendar_dates.txt` / `shapes.txt`). |
| 18 | //! Unzipping is a one-line pre-step (`unzip feed.zip -d <gtfs_dir>`); keeping |
| 19 | //! this tool zip-free means it builds with zero external crates and resolves |
| 20 | //! fully offline — the LANGUAGE RULE's Rust-first, no-Python requirement without |
| 21 | //! dragging in a decompression dep. |
| 22 | //! |
| 23 | //! Feeds merge into ONE pack: their GTFS ids are namespaced per feed so they |
| 24 | //! never collide, and cross-agency footpath transfers fall out of the merged |
| 25 | //! stop set for free. This is what makes a single global `world.transit` |
| 26 | //! feasible (see `src/index.rs` for the TRX2 format that keeps it small). |
| 27 | //! |
| 28 | //! GTFS feeds are sourced from the Transitous feed registry |
| 29 | //! (github.com/public-transport/transitous, `feeds/*.json`), which points at |
| 30 | //! each agency's official GTFS `.zip` — the same open data behind the P10 |
| 31 | //! online boards. See `scripts/maps/build_world_transit.ps1`. |
| 32 | |
| 33 | use gtfs_ingest::gtfs; |
| 34 | use gtfs_ingest::index; |
| 35 | use gtfs_ingest::index::FeedDir; |
| 36 | use gtfs_ingest::manifest::{read_manifest, parse_feed_spec, FeedSpec}; |
| 37 | use std::io::Write; |
| 38 | use std::path::{Path, PathBuf}; |
| 39 | use std::process::ExitCode; |
| 40 | |
| 41 | fn main() -> ExitCode { |
| 42 | let args: Vec<String> = std::env::args().collect(); |
| 43 | if args.len() < 4 { |
| 44 | eprintln!("usage: gtfs_ingest <out_dir> <pack_name> <feed>..."); |
| 45 | eprintln!(" gtfs_ingest <out_dir> <pack_name> --manifest <file>"); |
| 46 | eprintln!(" <feed> = feed_name=gtfs_dir[=motis_prefix] | gtfs_dir"); |
| 47 | return ExitCode::from(2); |
| 48 | } |
| 49 | let out_dir = PathBuf::from(&args[1]); |
| 50 | let pack_name = args[2].clone(); |
| 51 | |
| 52 | // Collect (feed_name, gtfs_dir, motis_prefix) triples, from a manifest or |
| 53 | // inline args. |
| 54 | let specs: Vec<FeedSpec> = if args[3] == "--manifest" { |
| 55 | let file = match args.get(4) { |
| 56 | Some(f) => f, |
| 57 | None => { |
| 58 | eprintln!("gtfs_ingest: --manifest requires a file path"); |
| 59 | return ExitCode::from(2); |
| 60 | } |
| 61 | }; |
| 62 | match read_manifest(Path::new(file)) { |
| 63 | Ok(v) => v, |
| 64 | Err(e) => { |
| 65 | eprintln!("gtfs_ingest: {e}"); |
| 66 | return ExitCode::FAILURE; |
| 67 | } |
| 68 | } |
| 69 | } else { |
| 70 | args[3..].iter().map(|s| parse_feed_spec(s)).collect() |
| 71 | }; |
| 72 | |
| 73 | if specs.is_empty() { |
| 74 | eprintln!("gtfs_ingest: no feeds given"); |
| 75 | return ExitCode::from(2); |
| 76 | } |
| 77 | |
| 78 | match run(&out_dir, &pack_name, &specs) { |
| 79 | Ok(()) => ExitCode::SUCCESS, |
| 80 | Err(e) => { |
| 81 | eprintln!("gtfs_ingest: {e}"); |
| 82 | ExitCode::FAILURE |
| 83 | } |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | fn run(out_dir: &Path, pack_name: &str, specs: &[FeedSpec]) -> Result<(), String> { |
| 88 | std::fs::create_dir_all(out_dir) |
| 89 | .map_err(|e| format!("cannot create out dir {}: {e}", out_dir.display()))?; |
| 90 | let index_path = out_dir.join(format!("{pack_name}.transit")); |
| 91 | // Straight to disk through a BufWriter: the pack is 1.5-4 GB for a world |
| 92 | // build, and holding a second copy of it in a `Vec` to then `fs::write` was |
| 93 | // pure overhead. |
| 94 | let file = std::fs::File::create(&index_path) |
| 95 | .map_err(|e| format!("cannot create {}: {e}", index_path.display()))?; |
| 96 | let mut writer = std::io::BufWriter::new(file); |
| 97 | |
| 98 | // Ingestion stays SERIAL and is overlapped with reading the next feed. |
| 99 | // |
| 100 | // `IndexBuilder` is one giant cross-feed accumulator — `StringPool::intern` hands |
| 101 | // back a byte offset that is written straight into section payloads, and |
| 102 | // `ROUTE_TRIPS` encodes `headsign_off` as a uvarint inside a varint stream — so |
| 103 | // sharding it would mean remapping every offset and re-encoding every trip list. |
| 104 | // Parsing CSV is the CPU cost; ingesting is pointer-shuffling. Overlapping the two |
| 105 | // gets most of the win for none of that risk and needs no format change. |
| 106 | // |
| 107 | // Depth ONE, deliberately. The comment above is the reason: a feed's tables cost |
| 108 | // several times the feed on disk, and parsing every feed up front is what made a |
| 109 | // world build need ~400 GB. One feed queued plus one being parsed plus one being |
| 110 | // ingested is three resident, and three is the most this is willing to spend |
| 111 | // without a measurement on real feeds to justify more. |
| 112 | let mut builder = index::IndexBuilder::new(pack_name); |
| 113 | let (tx, rx) = std::sync::mpsc::sync_channel::<Result<Loaded, String>>(1); |
| 114 | let total = specs.len(); |
| 115 | let result: Result<(), String> = std::thread::scope(|scope| { |
| 116 | scope.spawn(move || { |
| 117 | for spec in specs { |
| 118 | // A send failure means the consumer stopped, which happens only when |
| 119 | // it is already returning an error of its own. |
| 120 | if tx.send(load_feed(spec)).is_err() { |
| 121 | return; |
| 122 | } |
| 123 | } |
| 124 | }); |
| 125 | |
| 126 | for (n, loaded) in rx.iter().enumerate() { |
| 127 | let f = loaded?; |
| 128 | if f.shapes.is_none() { |
| 129 | eprintln!( |
| 130 | "gtfs_ingest: warning: feed '{}' has no shapes.txt; its ride legs \ |
| 131 | will draw stop-to-stop", |
| 132 | f.name |
| 133 | ); |
| 134 | } |
| 135 | if f.calendar.is_none() && f.calendar_dates.is_none() { |
| 136 | eprintln!( |
| 137 | "gtfs_ingest: warning: feed '{}' has no calendar.txt or \ |
| 138 | calendar_dates.txt; its services will never be scheduled", |
| 139 | f.name |
| 140 | ); |
| 141 | } |
| 142 | // Without a timezone the device falls back to its own, which is wrong |
| 143 | // for any feed outside the user's zone. |
| 144 | if f.agency.as_ref().is_none_or(|a| { |
| 145 | a.rows.first().is_none_or(|row| a.get(row, "agency_timezone").trim().is_empty()) |
| 146 | }) { |
| 147 | eprintln!( |
| 148 | "gtfs_ingest: warning: feed '{}' has no agency_timezone; \ |
| 149 | the device will route it in its own local time", |
| 150 | f.name |
| 151 | ); |
| 152 | } |
| 153 | builder.add_feed_dir(&FeedDir { |
| 154 | name: f.name.clone(), |
| 155 | motis_prefix: f.motis_prefix.clone(), |
| 156 | dir: &f.dir, |
| 157 | stops: &f.stops, |
| 158 | routes: &f.routes, |
| 159 | trips: &f.trips, |
| 160 | calendar: f.calendar.as_ref(), |
| 161 | calendar_dates: f.calendar_dates.as_ref(), |
| 162 | agency: f.agency.as_ref(), |
| 163 | shapes: f.shapes.as_ref(), |
| 164 | })?; |
| 165 | // Per feed, so a regression in the size or count curve shows at feed 200 |
| 166 | // rather than at hour six. |
| 167 | let (stops_so_far, routes_so_far, trips_so_far) = builder.counts(); |
| 168 | eprintln!( |
| 169 | "gtfs_ingest: [{}/{total}] {}: {:.1} MiB of sections, {stops_so_far} stops, \ |
| 170 | {routes_so_far} routes, {trips_so_far} trips", |
| 171 | n + 1, |
| 172 | f.name, |
| 173 | builder.section_bytes() as f64 / (1024.0 * 1024.0), |
| 174 | ); |
| 175 | } |
| 176 | Ok(()) |
| 177 | }); |
| 178 | result?; |
| 179 | |
| 180 | let stats = builder.finish_to(&mut writer)?; |
| 181 | writer |
| 182 | .flush() |
| 183 | .map_err(|e| format!("cannot finish writing {}: {e}", index_path.display()))?; |
| 184 | drop(writer); |
| 185 | |
| 186 | // Manifest (hand-written JSON, no serde dep). Includes a per-section size |
| 187 | // breakdown so the compression win (profiles vs the old stoptimes) is |
| 188 | // visible without extra tooling. |
| 189 | let sections_json = stats |
| 190 | .section_sizes |
| 191 | .iter() |
| 192 | .map(|(n, sz)| format!(" {}: {}", json_str(n), sz)) |
| 193 | .collect::<Vec<_>>() |
| 194 | .join(",\n"); |
| 195 | let manifest = format!( |
| 196 | "{{\n \"pack\": {pack},\n \"format_version\": {ver},\n \"file\": {file},\n \ |
| 197 | \"size_bytes\": {size},\n \"feeds\": {feeds},\n \"stops\": {stops},\n \ |
| 198 | \"routes\": {routes},\n \"trips\": {trips},\n \"profiles\": {profiles},\n \ |
| 199 | \"transfers\": {transfers},\n \"shaped_routes\": {shaped},\n \ |
| 200 | \"dropped_shape_routes\": {dropped},\n \ |
| 201 | \"dropped_stops_bad_coord\": {bad_coord},\n \ |
| 202 | \"bbox_e7\": [{min_lat}, {min_lon}, {max_lat}, {max_lon}],\n \ |
| 203 | \"section_bytes\": {{\n{sections}\n }}\n}}\n", |
| 204 | pack = json_str(pack_name), |
| 205 | ver = index::VERSION, |
| 206 | file = json_str(&format!("{pack_name}.transit")), |
| 207 | size = stats.size_bytes, |
| 208 | feeds = stats.feeds, |
| 209 | stops = stats.stops, |
| 210 | routes = stats.routes, |
| 211 | trips = stats.trips, |
| 212 | profiles = stats.profiles, |
| 213 | transfers = stats.transfers, |
| 214 | shaped = stats.shaped_routes, |
| 215 | dropped = stats.dropped_shape_routes, |
| 216 | bad_coord = stats.dropped_stops_bad_coord, |
| 217 | min_lat = stats.min_lat_e7, |
| 218 | min_lon = stats.min_lon_e7, |
| 219 | max_lat = stats.max_lat_e7, |
| 220 | max_lon = stats.max_lon_e7, |
| 221 | sections = sections_json, |
| 222 | ); |
| 223 | let manifest_path = out_dir.join(format!("{pack_name}.transit.json")); |
| 224 | std::fs::write(&manifest_path, manifest) |
| 225 | .map_err(|e| format!("cannot write {}: {e}", manifest_path.display()))?; |
| 226 | |
| 227 | eprintln!( |
| 228 | "gtfs_ingest: wrote {} ({:.1} MiB): {} feeds, {} stops, {} routes, {} trips, \ |
| 229 | {} profiles, {} transfers", |
| 230 | index_path.display(), |
| 231 | stats.size_bytes as f64 / (1024.0 * 1024.0), |
| 232 | stats.feeds, |
| 233 | stats.stops, |
| 234 | stats.routes, |
| 235 | stats.trips, |
| 236 | stats.profiles, |
| 237 | stats.transfers, |
| 238 | ); |
| 239 | eprintln!( |
| 240 | "gtfs_ingest: ride geometry: {} of {} routes shaped, {} dropped by validation, \ |
| 241 | {} with more than one shape_id", |
| 242 | stats.shaped_routes, stats.routes, stats.dropped_shape_routes, stats.multi_shape_routes, |
| 243 | ); |
| 244 | if stats.dropped_stops_bad_coord > 0 { |
| 245 | // Loud, because a coordinate outside the WGS84 ranges would otherwise |
| 246 | // saturate into the bbox and break the device's coverage test. |
| 247 | eprintln!( |
| 248 | "gtfs_ingest: warning: dropped {} stops with a missing or out-of-range \ |
| 249 | stop_lat/stop_lon", |
| 250 | stats.dropped_stops_bad_coord, |
| 251 | ); |
| 252 | } |
| 253 | Ok(()) |
| 254 | } |
| 255 | |
| 256 | /// One feed's tables, read off disk and owned. |
| 257 | /// |
| 258 | /// Exists so reading can happen on a different thread from ingesting: [`FeedDir`] |
| 259 | /// borrows, and a borrow cannot cross the channel that carries the feed to the |
| 260 | /// builder. |
| 261 | struct Loaded { |
| 262 | name: String, |
| 263 | motis_prefix: String, |
| 264 | dir: PathBuf, |
| 265 | stops: gtfs::Csv, |
| 266 | routes: gtfs::Csv, |
| 267 | trips: gtfs::Csv, |
| 268 | calendar: Option<gtfs::Csv>, |
| 269 | calendar_dates: Option<gtfs::Csv>, |
| 270 | agency: Option<gtfs::Csv>, |
| 271 | shapes: Option<std::collections::HashMap<String, gtfs::Shape>>, |
| 272 | } |
| 273 | |
| 274 | /// Read one feed's tables. `stop_times.txt` is NOT read here — `add_feed_dir` |
| 275 | /// streams it from `dir`, which is why the prefetch does not carry the largest file |
| 276 | /// in the feed and why its memory cost is bounded by the smaller tables. |
| 277 | fn load_feed(spec: &FeedSpec) -> Result<Loaded, String> { |
| 278 | let (name, dir, motis_prefix) = spec; |
| 279 | let require = |file: &str| -> Result<gtfs::Csv, String> { |
| 280 | gtfs::read_table(dir, file).ok_or_else(|| { |
| 281 | format!("feed '{name}' ({}) missing required GTFS file: {file}", dir.display()) |
| 282 | }) |
| 283 | }; |
| 284 | Ok(Loaded { |
| 285 | name: name.clone(), |
| 286 | motis_prefix: motis_prefix.clone(), |
| 287 | dir: dir.clone(), |
| 288 | stops: require("stops.txt")?, |
| 289 | routes: require("routes.txt")?, |
| 290 | trips: require("trips.txt")?, |
| 291 | calendar: gtfs::read_table(dir, "calendar.txt"), |
| 292 | calendar_dates: gtfs::read_table(dir, "calendar_dates.txt"), |
| 293 | agency: gtfs::read_table(dir, "agency.txt"), |
| 294 | shapes: gtfs::read_shapes(dir), |
| 295 | }) |
| 296 | } |
| 297 | |
| 298 | /// Minimal JSON string escaper for the manifest. |
| 299 | fn json_str(s: &str) -> String { |
| 300 | let mut out = String::with_capacity(s.len() + 2); |
| 301 | out.push('"'); |
| 302 | for c in s.chars() { |
| 303 | match c { |
| 304 | '"' => out.push_str("\\\""), |
| 305 | '\\' => out.push_str("\\\\"), |
| 306 | '\n' => out.push_str("\\n"), |
| 307 | '\r' => out.push_str("\\r"), |
| 308 | '\t' => out.push_str("\\t"), |
| 309 | c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), |
| 310 | c => out.push(c), |
| 311 | } |
| 312 | } |
| 313 | out.push('"'); |
| 314 | out |
| 315 | } |
| 316 | |
| 317 | #[cfg(test)] |
| 318 | mod tests { |
| 319 | use super::*; |
| 320 | |
| 321 | /// A minimal but complete GTFS feed, distinct per tag. |
| 322 | fn write_feed(root: &Path, tag: &str) -> PathBuf { |
| 323 | let dir = root.join(tag); |
| 324 | std::fs::create_dir_all(&dir).unwrap(); |
| 325 | let w = |file: &str, body: String| std::fs::write(dir.join(file), body).unwrap(); |
| 326 | w("agency.txt", format!("agency_id,agency_name,agency_timezone\nA{tag},Agency {tag},America/Los_Angeles\n")); |
| 327 | w("routes.txt", format!("route_id,agency_id,route_short_name,route_type\nR{tag},A{tag},{tag}1,3\n")); |
| 328 | w("trips.txt", format!("route_id,service_id,trip_id,trip_headsign\nR{tag},S{tag},T{tag},To {tag}\n")); |
| 329 | w("calendar.txt", format!("service_id,monday,tuesday,wednesday,thursday,friday,saturday,sunday,start_date,end_date\nS{tag},1,1,1,1,1,1,1,20260101,20271231\n")); |
| 330 | w("stops.txt", format!("stop_id,stop_name,stop_lat,stop_lon\nS{tag}1,Stop {tag} One,37.7{},-122.4{}\nS{tag}2,Stop {tag} Two,37.8{},-122.3{}\n", tag.len(), tag.len(), tag.len(), tag.len())); |
| 331 | w("stop_times.txt", format!("trip_id,arrival_time,departure_time,stop_id,stop_sequence\nT{tag},08:00:00,08:00:00,S{tag}1,1\nT{tag},08:10:00,08:10:00,S{tag}2,2\n")); |
| 332 | dir |
| 333 | } |
| 334 | |
| 335 | /// The pack must depend on feed ORDER and nothing else. |
| 336 | /// |
| 337 | /// Reading is pipelined onto another thread while `IndexBuilder` ingests, so the |
| 338 | /// thing that could break is the order `add_feed_dir` sees. Two assertions pin it: |
| 339 | /// the same specs twice must be byte-identical (the pipeline is deterministic), and |
| 340 | /// reversed specs must NOT be (order genuinely decides the string-pool offsets, so |
| 341 | /// the first assertion is not passing for trivial reasons). |
| 342 | #[test] |
| 343 | fn the_pack_is_deterministic_and_order_sensitive() { |
| 344 | let root = std::env::temp_dir().join(format!("gtfs_pack_{}", std::process::id())); |
| 345 | let _ = std::fs::remove_dir_all(&root); |
| 346 | let dirs: Vec<PathBuf> = ["a", "bb", "ccc", "dddd", "eeeee"] |
| 347 | .iter() |
| 348 | .map(|t| write_feed(&root, t)) |
| 349 | .collect(); |
| 350 | let specs: Vec<FeedSpec> = ["a", "bb", "ccc", "dddd", "eeeee"] |
| 351 | .iter() |
| 352 | .zip(&dirs) |
| 353 | .map(|(t, d)| (t.to_string(), d.clone(), format!("p{t}"))) |
| 354 | .collect(); |
| 355 | |
| 356 | let build = |name: &str, specs: &[FeedSpec]| -> Vec<u8> { |
| 357 | let out = root.join(name); |
| 358 | run(&out, "world", specs).unwrap(); |
| 359 | std::fs::read(out.join("world.transit")).unwrap() |
| 360 | }; |
| 361 | |
| 362 | let once = build("one", &specs); |
| 363 | let twice = build("two", &specs); |
| 364 | assert!(once == twice, "the pipelined pack build is not deterministic"); |
| 365 | |
| 366 | let mut reversed = specs.clone(); |
| 367 | reversed.reverse(); |
| 368 | let backwards = build("rev", &reversed); |
| 369 | assert!( |
| 370 | backwards != once, |
| 371 | "feed order does not affect the pack, so the determinism check above \ |
| 372 | proves nothing about ordering" |
| 373 | ); |
| 374 | let _ = std::fs::remove_dir_all(&root); |
| 375 | } |
| 376 | } |