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

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

registry.rs467 lines · 18.3 KiBRaw
1//! Resolving the Transitous registry against transitland-atlas, so a feed's stops
2//! can carry MOTIS ids.
3//!
4//! A port of the old `build_ca_transit.ps1`'s resolution (now deleted; the world
5//! build mirrors Transitous' published directory instead), generalised from one
6//! region file to a glob over all of them. `build_world_transit.sh` used to scrape `url` fields
7//! out of the registry, which silently dropped every source referenced only by
8//! `transitland-atlas-id` -- **38 of California's 49**. Worse, index-based feed names
9//! (`us_ca_0`, `us_ca_1`, …) meant its manifest was two-field, so nothing had a
10//! MOTIS prefix and live delays could never be matched to a stop.
11//!
12//! # Why the atlas is consulted even when the registry has a URL
13//!
14//! An agency is usually listed **twice** in the atlas: once for its schedule
15//! (`spec: gtfs`) and once for its realtime feed (`spec: gtfs-rt`). Only the atlas
16//! entry's `spec` distinguishes them. If the registry's `url-override` were trusted
17//! first, a realtime endpoint could win the dedup and knock the real schedule out of
18//! the build -- a feed silently missing its timetable, which is worse than a feed
19//! that is loudly absent. So the atlas entry is resolved and its `spec` checked
20//! before any URL is chosen.
21//!
22//! # URL precedence
23//!
24//! 1. `url-override` from the registry -- a deliberate correction, so it wins.
25//! 2. `url` from the registry.
26//! 3. `urls.static_current` from the atlas, **unless** the feed has an
27//! `authorization` block, in which case an unauthenticated fetch will fail.
28//! 4. The first `urls.static_historic` entry -- stale beats absent.
29//! 5. `static_current` anyway, as a last resort, flagged as likely to fail.
30//!
31//! # Two names per feed, and why
32//!
33//! [`Resolved::name`] is sanitised for use as a directory and a string-pool entry;
34//! [`Resolved::source`] is the registry's original name, which is what composes the
35//! MOTIS prefix. `SF-bayarea` sanitises to `sf_bayarea` and cannot be recovered from
36//! it, which is exactly why the two are carried separately and why the manifest has
37//! three fields.
38
39use crate::json::Json;
40
41/// One usable feed.
42#[derive(Debug, Clone, PartialEq)]
43pub struct Resolved {
44 /// Filename- and pool-safe. Also the manifest's first field.
45 pub name: String,
46 /// The registry's original source name, unmangled. Composes the MOTIS prefix.
47 pub source: String,
48 pub url: String,
49 /// Which rule chose the URL, for the report.
50 pub via: &'static str,
51}
52
53/// One source that could not be used, and why. Reported rather than dropped: a feed
54/// vanishing without explanation is how 38 of California's agencies went missing for
55/// as long as they did.
56#[derive(Debug, Clone, PartialEq)]
57pub struct Skipped {
58 pub name: String,
59 pub why: String,
60}
61
62#[derive(Debug, Default)]
63pub struct Resolution {
64 pub feeds: Vec<Resolved>,
65 pub skipped: Vec<Skipped>,
66 /// Sources seen across every region file.
67 pub considered: usize,
68}
69
70/// `Get-SafeName`: lowercase, and every run of non-alphanumerics becomes one `_`.
71pub fn safe_name(s: &str) -> String {
72 let mut out = String::with_capacity(s.len());
73 let mut pending = false;
74 for c in s.chars() {
75 if c.is_ascii_alphanumeric() {
76 if pending && !out.is_empty() {
77 out.push('_');
78 }
79 pending = false;
80 out.push(c.to_ascii_lowercase());
81 } else {
82 pending = true;
83 }
84 }
85 out
86}
87
88/// An index of every atlas feed by its id, built from the `*.dmfr.json` documents.
89pub fn index_atlas(docs: &[Json]) -> std::collections::HashMap<&str, &Json> {
90 let mut out = std::collections::HashMap::new();
91 for doc in docs {
92 for feed in doc.get("feeds").map(Json::as_array).unwrap_or_default() {
93 if let Some(id) = feed.get("id").and_then(Json::as_str) {
94 out.insert(id, feed);
95 }
96 }
97 }
98 out
99}
100
101/// A URL that is a realtime endpoint rather than a schedule zip.
102///
103/// Tests the **path**, not the whole URL, and treats a `.zip` as definitively
104/// static. `build_world_transit.sh` matched `*realtime*` against the whole URL,
105/// which threw away Golden Gate Transit's perfectly good schedule zip because it is
106/// served from `realtime.goldengate.org`.
107pub fn is_realtime(url: &str) -> bool {
108 let path = url.split('?').next().unwrap_or(url);
109 let lower = path.to_ascii_lowercase();
110 if lower.ends_with(".zip") {
111 return false;
112 }
113 lower.contains("gtfs-rt")
114 || lower.contains("gtfs_rt")
115 || lower.contains("gtfsrt")
116 || lower.ends_with(".pb")
117 || url.contains("feed_type=")
118}
119
120/// Resolve one registry region file's sources.
121///
122/// `region` is the file's base name (`us-ca`), which prefixes the MOTIS namespace.
123pub fn resolve_region(
124 region: &str,
125 registry: &Json,
126 atlas: &std::collections::HashMap<&str, &Json>,
127 out: &mut Resolution,
128) {
129 for s in registry.get("sources").map(Json::as_array).unwrap_or_default() {
130 out.considered += 1;
131 let atlas_id = s.get("transitland-atlas-id").and_then(Json::as_str);
132 let name = s.get("name").and_then(Json::as_str).or(atlas_id).unwrap_or("").to_string();
133 let mut skip = |why: String| out.skipped.push(Skipped { name: name.clone(), why });
134
135 if s.get("skip").is_some_and(Json::is_truthy) {
136 let reason = s.get("skip-reason").and_then(Json::as_str).unwrap_or("no reason given");
137 skip(format!("registry says skip: {reason}"));
138 continue;
139 }
140 if let Some(spec) = s.get("spec").and_then(Json::as_str) {
141 if spec != "gtfs" {
142 skip(format!("registry spec is {spec}"));
143 continue;
144 }
145 }
146 if name.is_empty() {
147 skip("source has neither a name nor an atlas id".to_string());
148 continue;
149 }
150
151 // The atlas entry is resolved BEFORE any URL is chosen. See the module docs.
152 let mut feed: Option<&Json> = None;
153 if let Some(id) = atlas_id {
154 match atlas.get(id) {
155 None => {
156 skip(format!("atlas id {id} is not in the atlas"));
157 continue;
158 }
159 Some(f) => {
160 match f.get("spec").and_then(Json::as_str) {
161 // A missing spec means gtfs, which is the atlas default.
162 None | Some("gtfs") => feed = Some(f),
163 Some(other) => {
164 skip(format!("atlas spec is {other}"));
165 continue;
166 }
167 }
168 }
169 }
170 }
171
172 let needs_key = feed.is_some_and(|f| f.get("authorization").is_some_and(Json::is_truthy));
173 let urls = feed.and_then(|f| f.get("urls"));
174 let current = urls.and_then(|u| u.get("static_current")).and_then(Json::as_str);
175 let historic = urls
176 .and_then(|u| u.get("static_historic"))
177 .map(Json::as_array)
178 .unwrap_or_default()
179 .iter()
180 .filter_map(Json::as_str)
181 .find(|u| !u.is_empty());
182
183 let chosen: Option<(&str, &'static str)> = s
184 .get("url-override")
185 .and_then(Json::as_str)
186 .filter(|u| !u.is_empty())
187 .map(|u| (u, "url-override"))
188 .or_else(|| {
189 s.get("url")
190 .and_then(Json::as_str)
191 .filter(|u| !u.is_empty())
192 .map(|u| (u, "registry url"))
193 })
194 .or_else(|| {
195 current.filter(|u| !u.is_empty() && !needs_key).map(|u| (u, "atlas static_current"))
196 })
197 .or_else(|| {
198 historic.map(|u| {
199 if needs_key {
200 (u, "atlas static_historic (static_current needs a key)")
201 } else {
202 (u, "atlas static_historic")
203 }
204 })
205 })
206 .or_else(|| {
207 current
208 .filter(|u| !u.is_empty())
209 .map(|u| (u, "atlas static_current (needs a key; will likely fail)"))
210 });
211
212 let Some((url, via)) = chosen else {
213 skip("no usable GTFS URL".to_string());
214 continue;
215 };
216 if is_realtime(url) {
217 skip(format!("URL is a realtime endpoint: {url}"));
218 continue;
219 }
220
221 out.feeds.push(Resolved {
222 name: safe_name(&name),
223 source: format!("{region}-{name}"),
224 url: url.to_string(),
225 via,
226 });
227 }
228}
229
230/// Drop duplicates, keeping the first of each name and then of each URL.
231///
232/// Two passes because they catch different things: the same agency listed in two
233/// region files shares a name, and two differently-named sources pointing at one
234/// combined feed share a URL. Both would otherwise be downloaded and merged twice.
235pub fn dedup(feeds: &mut Vec<Resolved>) {
236 let mut names = std::collections::HashSet::new();
237 feeds.retain(|f| names.insert(f.name.clone()));
238 let mut urls = std::collections::HashSet::new();
239 feeds.retain(|f| urls.insert(f.url.clone()));
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245 use crate::json;
246
247 fn atlas_docs(text: &str) -> Vec<Json> {
248 vec![json::parse(text).unwrap()]
249 }
250
251 fn resolve(region_text: &str, atlas_text: &str) -> Resolution {
252 let docs = atlas_docs(atlas_text);
253 let atlas = index_atlas(&docs);
254 let registry = json::parse(region_text).unwrap();
255 let mut out = Resolution::default();
256 resolve_region("us-ca", &registry, &atlas, &mut out);
257 out
258 }
259
260 const ATLAS: &str = r#"{"feeds":[
261 {"id":"f-static","spec":"gtfs","urls":{"static_current":"https://a/sched.zip"}},
262 {"id":"f-rt","spec":"gtfs-rt","urls":{"static_current":"https://a/rt.pb"}},
263 {"id":"f-keyed","spec":"gtfs","authorization":{"type":"query_param"},
264 "urls":{"static_current":"https://a/keyed.zip",
265 "static_historic":["https://a/old.zip"]}},
266 {"id":"f-nospec","urls":{"static_current":"https://a/nospec.zip"}},
267 {"id":"f-nourl","spec":"gtfs","urls":{}}
268 ]}"#;
269
270 #[test]
271 fn safe_name_matches_get_safe_name() {
272 assert_eq!(safe_name("SF-bayarea"), "sf_bayarea");
273 assert_eq!(safe_name("Golden Gate Transit"), "golden_gate_transit");
274 assert_eq!(safe_name("--leading and trailing--"), "leading_and_trailing");
275 assert_eq!(safe_name("a...b"), "a_b");
276 assert_eq!(safe_name("ALLCAPS"), "allcaps");
277 assert_eq!(safe_name(""), "");
278 assert_eq!(safe_name("---"), "");
279 }
280
281 #[test]
282 fn a_source_referenced_only_by_atlas_id_resolves() {
283 // The whole point: build_world_transit.sh dropped these, 38 of 49 in CA.
284 let r = resolve(r#"{"sources":[{"transitland-atlas-id":"f-static"}]}"#, ATLAS);
285 assert_eq!(r.feeds.len(), 1, "{:?}", r.skipped);
286 assert_eq!(r.feeds[0].url, "https://a/sched.zip");
287 assert_eq!(r.feeds[0].via, "atlas static_current");
288 // The name falls back to the atlas id when the registry gives none.
289 assert_eq!(r.feeds[0].name, "f_static");
290 assert_eq!(r.feeds[0].source, "us-ca-f-static");
291 }
292
293 #[test]
294 fn the_motis_prefix_keeps_the_unmangled_source_name() {
295 let r = resolve(
296 r#"{"sources":[{"name":"SF-bayarea","transitland-atlas-id":"f-static"}]}"#,
297 ATLAS,
298 );
299 // Sanitising is lossy, which is why both names are carried.
300 assert_eq!(r.feeds[0].name, "sf_bayarea");
301 assert_eq!(r.feeds[0].source, "us-ca-SF-bayarea");
302 }
303
304 #[test]
305 fn url_precedence_runs_override_registry_current_historic() {
306 let r = resolve(
307 r#"{"sources":[{"name":"A","transitland-atlas-id":"f-static",
308 "url-override":"https://o/x.zip","url":"https://r/x.zip"}]}"#,
309 ATLAS,
310 );
311 assert_eq!(r.feeds[0].url, "https://o/x.zip");
312 assert_eq!(r.feeds[0].via, "url-override");
313
314 let r = resolve(
315 r#"{"sources":[{"name":"A","transitland-atlas-id":"f-static","url":"https://r/x.zip"}]}"#,
316 ATLAS,
317 );
318 assert_eq!(r.feeds[0].url, "https://r/x.zip");
319 assert_eq!(r.feeds[0].via, "registry url");
320 }
321
322 #[test]
323 fn an_authorized_feed_prefers_a_historic_url_over_one_needing_a_key() {
324 // static_current would 401. Stale beats absent.
325 let r = resolve(r#"{"sources":[{"name":"K","transitland-atlas-id":"f-keyed"}]}"#, ATLAS);
326 assert_eq!(r.feeds[0].url, "https://a/old.zip");
327 assert_eq!(r.feeds[0].via, "atlas static_historic (static_current needs a key)");
328 }
329
330 #[test]
331 fn a_keyed_feed_with_no_history_falls_back_and_says_so() {
332 let atlas = atlas_docs(
333 r#"{"feeds":[{"id":"f-k","spec":"gtfs","authorization":{"type":"header"},
334 "urls":{"static_current":"https://a/keyed.zip"}}]}"#,
335 );
336 let index = index_atlas(&atlas);
337 let mut out = Resolution::default();
338 resolve_region(
339 "us-ca",
340 &json::parse(r#"{"sources":[{"name":"K","transitland-atlas-id":"f-k"}]}"#).unwrap(),
341 &index,
342 &mut out,
343 );
344 assert_eq!(out.feeds[0].url, "https://a/keyed.zip");
345 assert!(out.feeds[0].via.contains("will likely fail"));
346 }
347
348 #[test]
349 fn the_atlas_spec_is_checked_before_any_url_is_chosen() {
350 // A realtime atlas entry is refused even though the registry supplies a
351 // perfectly fetchable override. Trusting the override first is how a
352 // realtime endpoint wins the dedup and knocks out the real schedule.
353 let r = resolve(
354 r#"{"sources":[{"name":"RT","transitland-atlas-id":"f-rt",
355 "url-override":"https://o/looks-fine.zip"}]}"#,
356 ATLAS,
357 );
358 assert!(r.feeds.is_empty(), "{:?}", r.feeds);
359 assert_eq!(r.skipped.len(), 1);
360 assert!(r.skipped[0].why.contains("atlas spec is gtfs-rt"), "{:?}", r.skipped);
361 }
362
363 #[test]
364 fn a_missing_atlas_spec_counts_as_gtfs() {
365 let r = resolve(r#"{"sources":[{"name":"N","transitland-atlas-id":"f-nospec"}]}"#, ATLAS);
366 assert_eq!(r.feeds.len(), 1, "{:?}", r.skipped);
367 assert_eq!(r.feeds[0].url, "https://a/nospec.zip");
368 }
369
370 #[test]
371 fn every_skip_reason_is_reported_rather_than_silent() {
372 let cases = [
373 (
374 r#"{"sources":[{"name":"S","skip":true,"skip-reason":"broken since 2019"}]}"#,
375 "registry says skip: broken since 2019",
376 ),
377 (
378 r#"{"sources":[{"name":"S","spec":"gtfs-rt","url":"https://a/x.zip"}]}"#,
379 "registry spec is gtfs-rt",
380 ),
381 (
382 r#"{"sources":[{"name":"S","transitland-atlas-id":"f-missing"}]}"#,
383 "atlas id f-missing is not in the atlas",
384 ),
385 (
386 r#"{"sources":[{"name":"S","transitland-atlas-id":"f-nourl"}]}"#,
387 "no usable GTFS URL",
388 ),
389 (r#"{"sources":[{"name":"S"}]}"#, "no usable GTFS URL"),
390 (r#"{"sources":[{"url":"https://a/x.zip"}]}"#, "neither a name nor an atlas id"),
391 ];
392 for (text, want) in cases {
393 let r = resolve(text, ATLAS);
394 assert!(r.feeds.is_empty(), "{text} should not resolve");
395 assert_eq!(r.skipped.len(), 1, "{text}");
396 assert!(
397 r.skipped[0].why.contains(want),
398 "{text}: wanted {want:?}, got {:?}",
399 r.skipped[0].why
400 );
401 }
402 }
403
404 #[test]
405 fn realtime_detection_looks_at_the_path_and_spares_zips() {
406 // The Golden Gate case: a schedule zip on a host called `realtime`.
407 assert!(!is_realtime("https://realtime.goldengate.org/gtfs/sched.zip"));
408 assert!(!is_realtime("https://a/gtfs.zip?key=1"));
409 // Genuine realtime endpoints.
410 assert!(is_realtime("https://a/gtfs-rt/trips"));
411 assert!(is_realtime("https://a/gtfs_rt?agency=x"));
412 assert!(is_realtime("https://a/gtfsrt/vehicles"));
413 assert!(is_realtime("https://a/feed.pb"));
414 assert!(is_realtime("https://a/api/feed?feed_type=trip"));
415 // A query string alone does not make it realtime.
416 assert!(!is_realtime("https://a/download?agency=x"));
417 }
418
419 #[test]
420 fn a_realtime_url_is_skipped_even_when_the_atlas_says_gtfs() {
421 let r = resolve(
422 r#"{"sources":[{"name":"R","transitland-atlas-id":"f-static",
423 "url-override":"https://a/gtfs-rt/trips"}]}"#,
424 ATLAS,
425 );
426 assert!(r.feeds.is_empty());
427 assert!(r.skipped[0].why.contains("realtime endpoint"));
428 }
429
430 #[test]
431 fn dedup_drops_repeats_by_name_then_by_url() {
432 let mut feeds = vec![
433 Resolved { name: "a".into(), source: "r-A".into(), url: "u1".into(), via: "x" },
434 // Same name from another region file.
435 Resolved { name: "a".into(), source: "s-A".into(), url: "u2".into(), via: "x" },
436 // Different name, same combined feed.
437 Resolved { name: "b".into(), source: "r-B".into(), url: "u1".into(), via: "x" },
438 Resolved { name: "c".into(), source: "r-C".into(), url: "u3".into(), via: "x" },
439 ];
440 dedup(&mut feeds);
441 assert_eq!(feeds.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["a", "c"]);
442 // The first of each is the one kept, so the result is order-stable.
443 assert_eq!(feeds[0].source, "r-A");
444 }
445
446 #[test]
447 fn a_registry_with_no_sources_resolves_to_nothing_without_erroring() {
448 let r = resolve("{}", ATLAS);
449 assert_eq!(r.considered, 0);
450 assert!(r.feeds.is_empty() && r.skipped.is_empty());
451 let r = resolve(r#"{"sources":[]}"#, ATLAS);
452 assert_eq!(r.considered, 0);
453 }
454
455 #[test]
456 fn the_atlas_index_covers_every_document() {
457 let docs = vec![
458 json::parse(r#"{"feeds":[{"id":"a"},{"id":"b"}]}"#).unwrap(),
459 json::parse(r#"{"feeds":[{"id":"c"}]}"#).unwrap(),
460 // A document with no feeds must not break the index.
461 json::parse(r#"{"license":{}}"#).unwrap(),
462 ];
463 let index = index_atlas(&docs);
464 assert_eq!(index.len(), 3);
465 assert!(index.contains_key("a") && index.contains_key("c"));
466 }
467}