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

Modern-Apps.git / scripts / maps / gtfs_ingest / src / main.rs

main.rs383 lines · 16.0 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
33use gtfs_ingest::gtfs;
34use gtfs_ingest::index;
35use gtfs_ingest::index::FeedDir;
36use gtfs_ingest::manifest::{parse_feed_spec, read_manifest, FeedSpec};
37use std::io::Write;
38use std::path::{Path, PathBuf};
39use std::process::ExitCode;
40
41fn 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
87fn 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.flush().map_err(|e| format!("cannot finish writing {}: {e}", index_path.display()))?;
182 drop(writer);
183
184 // Manifest (hand-written JSON, no serde dep). Includes a per-section size
185 // breakdown so the compression win (profiles vs the old stoptimes) is
186 // visible without extra tooling.
187 let sections_json = stats
188 .section_sizes
189 .iter()
190 .map(|(n, sz)| format!(" {}: {}", json_str(n), sz))
191 .collect::<Vec<_>>()
192 .join(",\n");
193 let manifest = format!(
194 "{{\n \"pack\": {pack},\n \"format_version\": {ver},\n \"file\": {file},\n \
195 \"size_bytes\": {size},\n \"feeds\": {feeds},\n \"stops\": {stops},\n \
196 \"routes\": {routes},\n \"trips\": {trips},\n \"profiles\": {profiles},\n \
197 \"transfers\": {transfers},\n \"shaped_routes\": {shaped},\n \
198 \"dropped_shape_routes\": {dropped},\n \
199 \"dropped_stops_bad_coord\": {bad_coord},\n \
200 \"bbox_e7\": [{min_lat}, {min_lon}, {max_lat}, {max_lon}],\n \
201 \"section_bytes\": {{\n{sections}\n }}\n}}\n",
202 pack = json_str(pack_name),
203 ver = index::VERSION,
204 file = json_str(&format!("{pack_name}.transit")),
205 size = stats.size_bytes,
206 feeds = stats.feeds,
207 stops = stats.stops,
208 routes = stats.routes,
209 trips = stats.trips,
210 profiles = stats.profiles,
211 transfers = stats.transfers,
212 shaped = stats.shaped_routes,
213 dropped = stats.dropped_shape_routes,
214 bad_coord = stats.dropped_stops_bad_coord,
215 min_lat = stats.min_lat_e7,
216 min_lon = stats.min_lon_e7,
217 max_lat = stats.max_lat_e7,
218 max_lon = stats.max_lon_e7,
219 sections = sections_json,
220 );
221 let manifest_path = out_dir.join(format!("{pack_name}.transit.json"));
222 std::fs::write(&manifest_path, manifest)
223 .map_err(|e| format!("cannot write {}: {e}", manifest_path.display()))?;
224
225 eprintln!(
226 "gtfs_ingest: wrote {} ({:.1} MiB): {} feeds, {} stops, {} routes, {} trips, \
227 {} profiles, {} transfers",
228 index_path.display(),
229 stats.size_bytes as f64 / (1024.0 * 1024.0),
230 stats.feeds,
231 stats.stops,
232 stats.routes,
233 stats.trips,
234 stats.profiles,
235 stats.transfers,
236 );
237 eprintln!(
238 "gtfs_ingest: ride geometry: {} of {} routes shaped, {} dropped by validation, \
239 {} with more than one shape_id",
240 stats.shaped_routes, stats.routes, stats.dropped_shape_routes, stats.multi_shape_routes,
241 );
242 if stats.dropped_stops_bad_coord > 0 {
243 // Loud, because a coordinate outside the WGS84 ranges would otherwise
244 // saturate into the bbox and break the device's coverage test.
245 eprintln!(
246 "gtfs_ingest: warning: dropped {} stops with a missing or out-of-range \
247 stop_lat/stop_lon",
248 stats.dropped_stops_bad_coord,
249 );
250 }
251 Ok(())
252}
253
254/// One feed's tables, read off disk and owned.
255///
256/// Exists so reading can happen on a different thread from ingesting: [`FeedDir`]
257/// borrows, and a borrow cannot cross the channel that carries the feed to the
258/// builder.
259struct Loaded {
260 name: String,
261 motis_prefix: String,
262 dir: PathBuf,
263 stops: gtfs::Csv,
264 routes: gtfs::Csv,
265 trips: gtfs::Csv,
266 calendar: Option<gtfs::Csv>,
267 calendar_dates: Option<gtfs::Csv>,
268 agency: Option<gtfs::Csv>,
269 shapes: Option<std::collections::HashMap<String, gtfs::Shape>>,
270}
271
272/// Read one feed's tables. `stop_times.txt` is NOT read here — `add_feed_dir`
273/// streams it from `dir`, which is why the prefetch does not carry the largest file
274/// in the feed and why its memory cost is bounded by the smaller tables.
275fn load_feed(spec: &FeedSpec) -> Result<Loaded, String> {
276 let (name, dir, motis_prefix) = spec;
277 let require = |file: &str| -> Result<gtfs::Csv, String> {
278 gtfs::read_table(dir, file).ok_or_else(|| {
279 format!("feed '{name}' ({}) missing required GTFS file: {file}", dir.display())
280 })
281 };
282 Ok(Loaded {
283 name: name.clone(),
284 motis_prefix: motis_prefix.clone(),
285 dir: dir.clone(),
286 stops: require("stops.txt")?,
287 routes: require("routes.txt")?,
288 trips: require("trips.txt")?,
289 calendar: gtfs::read_table(dir, "calendar.txt"),
290 calendar_dates: gtfs::read_table(dir, "calendar_dates.txt"),
291 agency: gtfs::read_table(dir, "agency.txt"),
292 shapes: gtfs::read_shapes(dir),
293 })
294}
295
296/// Minimal JSON string escaper for the manifest.
297fn json_str(s: &str) -> String {
298 let mut out = String::with_capacity(s.len() + 2);
299 out.push('"');
300 for c in s.chars() {
301 match c {
302 '"' => out.push_str("\\\""),
303 '\\' => out.push_str("\\\\"),
304 '\n' => out.push_str("\\n"),
305 '\r' => out.push_str("\\r"),
306 '\t' => out.push_str("\\t"),
307 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
308 c => out.push(c),
309 }
310 }
311 out.push('"');
312 out
313}
314
315#[cfg(test)]
316mod tests {
317 use super::*;
318
319 /// A minimal but complete GTFS feed, distinct per tag.
320 fn write_feed(root: &Path, tag: &str) -> PathBuf {
321 let dir = root.join(tag);
322 std::fs::create_dir_all(&dir).unwrap();
323 let w = |file: &str, body: String| std::fs::write(dir.join(file), body).unwrap();
324 w(
325 "agency.txt",
326 format!(
327 "agency_id,agency_name,agency_timezone\nA{tag},Agency {tag},America/Los_Angeles\n"
328 ),
329 );
330 w(
331 "routes.txt",
332 format!("route_id,agency_id,route_short_name,route_type\nR{tag},A{tag},{tag}1,3\n"),
333 );
334 w(
335 "trips.txt",
336 format!("route_id,service_id,trip_id,trip_headsign\nR{tag},S{tag},T{tag},To {tag}\n"),
337 );
338 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"));
339 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()));
340 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"));
341 dir
342 }
343
344 /// The pack must depend on feed ORDER and nothing else.
345 ///
346 /// Reading is pipelined onto another thread while `IndexBuilder` ingests, so the
347 /// thing that could break is the order `add_feed_dir` sees. Two assertions pin it:
348 /// the same specs twice must be byte-identical (the pipeline is deterministic), and
349 /// reversed specs must NOT be (order genuinely decides the string-pool offsets, so
350 /// the first assertion is not passing for trivial reasons).
351 #[test]
352 fn the_pack_is_deterministic_and_order_sensitive() {
353 let root = std::env::temp_dir().join(format!("gtfs_pack_{}", std::process::id()));
354 let _ = std::fs::remove_dir_all(&root);
355 let dirs: Vec<PathBuf> =
356 ["a", "bb", "ccc", "dddd", "eeeee"].iter().map(|t| write_feed(&root, t)).collect();
357 let specs: Vec<FeedSpec> = ["a", "bb", "ccc", "dddd", "eeeee"]
358 .iter()
359 .zip(&dirs)
360 .map(|(t, d)| (t.to_string(), d.clone(), format!("p{t}")))
361 .collect();
362
363 let build = |name: &str, specs: &[FeedSpec]| -> Vec<u8> {
364 let out = root.join(name);
365 run(&out, "world", specs).unwrap();
366 std::fs::read(out.join("world.transit")).unwrap()
367 };
368
369 let once = build("one", &specs);
370 let twice = build("two", &specs);
371 assert!(once == twice, "the pipelined pack build is not deterministic");
372
373 let mut reversed = specs.clone();
374 reversed.reverse();
375 let backwards = build("rev", &reversed);
376 assert!(
377 backwards != once,
378 "feed order does not affect the pack, so the determinism check above \
379 proves nothing about ordering"
380 );
381 let _ = std::fs::remove_dir_all(&root);
382 }
383}