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

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

registry.rs480 lines · 18.5 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
133 .get("name")
134 .and_then(Json::as_str)
135 .or(atlas_id)
136 .unwrap_or("")
137 .to_string();
138 let mut skip = |why: String| out.skipped.push(Skipped { name: name.clone(), why });
139
140 if s.get("skip").is_some_and(Json::is_truthy) {
141 let reason = s
142 .get("skip-reason")
143 .and_then(Json::as_str)
144 .unwrap_or("no reason given");
145 skip(format!("registry says skip: {reason}"));
146 continue;
147 }
148 if let Some(spec) = s.get("spec").and_then(Json::as_str) {
149 if spec != "gtfs" {
150 skip(format!("registry spec is {spec}"));
151 continue;
152 }
153 }
154 if name.is_empty() {
155 skip("source has neither a name nor an atlas id".to_string());
156 continue;
157 }
158
159 // The atlas entry is resolved BEFORE any URL is chosen. See the module docs.
160 let mut feed: Option<&Json> = None;
161 if let Some(id) = atlas_id {
162 match atlas.get(id) {
163 None => {
164 skip(format!("atlas id {id} is not in the atlas"));
165 continue;
166 }
167 Some(f) => {
168 match f.get("spec").and_then(Json::as_str) {
169 // A missing spec means gtfs, which is the atlas default.
170 None | Some("gtfs") => feed = Some(f),
171 Some(other) => {
172 skip(format!("atlas spec is {other}"));
173 continue;
174 }
175 }
176 }
177 }
178 }
179
180 let needs_key = feed.is_some_and(|f| f.get("authorization").is_some_and(Json::is_truthy));
181 let urls = feed.and_then(|f| f.get("urls"));
182 let current = urls.and_then(|u| u.get("static_current")).and_then(Json::as_str);
183 let historic = urls
184 .and_then(|u| u.get("static_historic"))
185 .map(Json::as_array)
186 .unwrap_or_default()
187 .iter()
188 .filter_map(Json::as_str)
189 .find(|u| !u.is_empty());
190
191 let chosen: Option<(&str, &'static str)> = s
192 .get("url-override")
193 .and_then(Json::as_str)
194 .filter(|u| !u.is_empty())
195 .map(|u| (u, "url-override"))
196 .or_else(|| {
197 s.get("url")
198 .and_then(Json::as_str)
199 .filter(|u| !u.is_empty())
200 .map(|u| (u, "registry url"))
201 })
202 .or_else(|| {
203 current
204 .filter(|u| !u.is_empty() && !needs_key)
205 .map(|u| (u, "atlas static_current"))
206 })
207 .or_else(|| {
208 historic.map(|u| {
209 if needs_key {
210 (u, "atlas static_historic (static_current needs a key)")
211 } else {
212 (u, "atlas static_historic")
213 }
214 })
215 })
216 .or_else(|| {
217 current
218 .filter(|u| !u.is_empty())
219 .map(|u| (u, "atlas static_current (needs a key; will likely fail)"))
220 });
221
222 let Some((url, via)) = chosen else {
223 skip("no usable GTFS URL".to_string());
224 continue;
225 };
226 if is_realtime(url) {
227 skip(format!("URL is a realtime endpoint: {url}"));
228 continue;
229 }
230
231 out.feeds.push(Resolved {
232 name: safe_name(&name),
233 source: format!("{region}-{name}"),
234 url: url.to_string(),
235 via,
236 });
237 }
238}
239
240/// Drop duplicates, keeping the first of each name and then of each URL.
241///
242/// Two passes because they catch different things: the same agency listed in two
243/// region files shares a name, and two differently-named sources pointing at one
244/// combined feed share a URL. Both would otherwise be downloaded and merged twice.
245pub fn dedup(feeds: &mut Vec<Resolved>) {
246 let mut names = std::collections::HashSet::new();
247 feeds.retain(|f| names.insert(f.name.clone()));
248 let mut urls = std::collections::HashSet::new();
249 feeds.retain(|f| urls.insert(f.url.clone()));
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255 use crate::json;
256
257 fn atlas_docs(text: &str) -> Vec<Json> {
258 vec![json::parse(text).unwrap()]
259 }
260
261 fn resolve(region_text: &str, atlas_text: &str) -> Resolution {
262 let docs = atlas_docs(atlas_text);
263 let atlas = index_atlas(&docs);
264 let registry = json::parse(region_text).unwrap();
265 let mut out = Resolution::default();
266 resolve_region("us-ca", &registry, &atlas, &mut out);
267 out
268 }
269
270 const ATLAS: &str = r#"{"feeds":[
271 {"id":"f-static","spec":"gtfs","urls":{"static_current":"https://a/sched.zip"}},
272 {"id":"f-rt","spec":"gtfs-rt","urls":{"static_current":"https://a/rt.pb"}},
273 {"id":"f-keyed","spec":"gtfs","authorization":{"type":"query_param"},
274 "urls":{"static_current":"https://a/keyed.zip",
275 "static_historic":["https://a/old.zip"]}},
276 {"id":"f-nospec","urls":{"static_current":"https://a/nospec.zip"}},
277 {"id":"f-nourl","spec":"gtfs","urls":{}}
278 ]}"#;
279
280 #[test]
281 fn safe_name_matches_get_safe_name() {
282 assert_eq!(safe_name("SF-bayarea"), "sf_bayarea");
283 assert_eq!(safe_name("Golden Gate Transit"), "golden_gate_transit");
284 assert_eq!(safe_name("--leading and trailing--"), "leading_and_trailing");
285 assert_eq!(safe_name("a...b"), "a_b");
286 assert_eq!(safe_name("ALLCAPS"), "allcaps");
287 assert_eq!(safe_name(""), "");
288 assert_eq!(safe_name("---"), "");
289 }
290
291 #[test]
292 fn a_source_referenced_only_by_atlas_id_resolves() {
293 // The whole point: build_world_transit.sh dropped these, 38 of 49 in CA.
294 let r = resolve(r#"{"sources":[{"transitland-atlas-id":"f-static"}]}"#, ATLAS);
295 assert_eq!(r.feeds.len(), 1, "{:?}", r.skipped);
296 assert_eq!(r.feeds[0].url, "https://a/sched.zip");
297 assert_eq!(r.feeds[0].via, "atlas static_current");
298 // The name falls back to the atlas id when the registry gives none.
299 assert_eq!(r.feeds[0].name, "f_static");
300 assert_eq!(r.feeds[0].source, "us-ca-f-static");
301 }
302
303 #[test]
304 fn the_motis_prefix_keeps_the_unmangled_source_name() {
305 let r = resolve(
306 r#"{"sources":[{"name":"SF-bayarea","transitland-atlas-id":"f-static"}]}"#,
307 ATLAS,
308 );
309 // Sanitising is lossy, which is why both names are carried.
310 assert_eq!(r.feeds[0].name, "sf_bayarea");
311 assert_eq!(r.feeds[0].source, "us-ca-SF-bayarea");
312 }
313
314 #[test]
315 fn url_precedence_runs_override_registry_current_historic() {
316 let r = resolve(
317 r#"{"sources":[{"name":"A","transitland-atlas-id":"f-static",
318 "url-override":"https://o/x.zip","url":"https://r/x.zip"}]}"#,
319 ATLAS,
320 );
321 assert_eq!(r.feeds[0].url, "https://o/x.zip");
322 assert_eq!(r.feeds[0].via, "url-override");
323
324 let r = resolve(
325 r#"{"sources":[{"name":"A","transitland-atlas-id":"f-static","url":"https://r/x.zip"}]}"#,
326 ATLAS,
327 );
328 assert_eq!(r.feeds[0].url, "https://r/x.zip");
329 assert_eq!(r.feeds[0].via, "registry url");
330 }
331
332 #[test]
333 fn an_authorized_feed_prefers_a_historic_url_over_one_needing_a_key() {
334 // static_current would 401. Stale beats absent.
335 let r = resolve(r#"{"sources":[{"name":"K","transitland-atlas-id":"f-keyed"}]}"#, ATLAS);
336 assert_eq!(r.feeds[0].url, "https://a/old.zip");
337 assert_eq!(r.feeds[0].via, "atlas static_historic (static_current needs a key)");
338 }
339
340 #[test]
341 fn a_keyed_feed_with_no_history_falls_back_and_says_so() {
342 let atlas = atlas_docs(
343 r#"{"feeds":[{"id":"f-k","spec":"gtfs","authorization":{"type":"header"},
344 "urls":{"static_current":"https://a/keyed.zip"}}]}"#,
345 );
346 let index = index_atlas(&atlas);
347 let mut out = Resolution::default();
348 resolve_region(
349 "us-ca",
350 &json::parse(r#"{"sources":[{"name":"K","transitland-atlas-id":"f-k"}]}"#).unwrap(),
351 &index,
352 &mut out,
353 );
354 assert_eq!(out.feeds[0].url, "https://a/keyed.zip");
355 assert!(out.feeds[0].via.contains("will likely fail"));
356 }
357
358 #[test]
359 fn the_atlas_spec_is_checked_before_any_url_is_chosen() {
360 // A realtime atlas entry is refused even though the registry supplies a
361 // perfectly fetchable override. Trusting the override first is how a
362 // realtime endpoint wins the dedup and knocks out the real schedule.
363 let r = resolve(
364 r#"{"sources":[{"name":"RT","transitland-atlas-id":"f-rt",
365 "url-override":"https://o/looks-fine.zip"}]}"#,
366 ATLAS,
367 );
368 assert!(r.feeds.is_empty(), "{:?}", r.feeds);
369 assert_eq!(r.skipped.len(), 1);
370 assert!(r.skipped[0].why.contains("atlas spec is gtfs-rt"), "{:?}", r.skipped);
371 }
372
373 #[test]
374 fn a_missing_atlas_spec_counts_as_gtfs() {
375 let r = resolve(r#"{"sources":[{"name":"N","transitland-atlas-id":"f-nospec"}]}"#, ATLAS);
376 assert_eq!(r.feeds.len(), 1, "{:?}", r.skipped);
377 assert_eq!(r.feeds[0].url, "https://a/nospec.zip");
378 }
379
380 #[test]
381 fn every_skip_reason_is_reported_rather_than_silent() {
382 let cases = [
383 (
384 r#"{"sources":[{"name":"S","skip":true,"skip-reason":"broken since 2019"}]}"#,
385 "registry says skip: broken since 2019",
386 ),
387 (
388 r#"{"sources":[{"name":"S","spec":"gtfs-rt","url":"https://a/x.zip"}]}"#,
389 "registry spec is gtfs-rt",
390 ),
391 (
392 r#"{"sources":[{"name":"S","transitland-atlas-id":"f-missing"}]}"#,
393 "atlas id f-missing is not in the atlas",
394 ),
395 (
396 r#"{"sources":[{"name":"S","transitland-atlas-id":"f-nourl"}]}"#,
397 "no usable GTFS URL",
398 ),
399 (r#"{"sources":[{"name":"S"}]}"#, "no usable GTFS URL"),
400 (r#"{"sources":[{"url":"https://a/x.zip"}]}"#, "neither a name nor an atlas id"),
401 ];
402 for (text, want) in cases {
403 let r = resolve(text, ATLAS);
404 assert!(r.feeds.is_empty(), "{text} should not resolve");
405 assert_eq!(r.skipped.len(), 1, "{text}");
406 assert!(
407 r.skipped[0].why.contains(want),
408 "{text}: wanted {want:?}, got {:?}",
409 r.skipped[0].why
410 );
411 }
412 }
413
414 #[test]
415 fn realtime_detection_looks_at_the_path_and_spares_zips() {
416 // The Golden Gate case: a schedule zip on a host called `realtime`.
417 assert!(!is_realtime("https://realtime.goldengate.org/gtfs/sched.zip"));
418 assert!(!is_realtime("https://a/gtfs.zip?key=1"));
419 // Genuine realtime endpoints.
420 assert!(is_realtime("https://a/gtfs-rt/trips"));
421 assert!(is_realtime("https://a/gtfs_rt?agency=x"));
422 assert!(is_realtime("https://a/gtfsrt/vehicles"));
423 assert!(is_realtime("https://a/feed.pb"));
424 assert!(is_realtime("https://a/api/feed?feed_type=trip"));
425 // A query string alone does not make it realtime.
426 assert!(!is_realtime("https://a/download?agency=x"));
427 }
428
429 #[test]
430 fn a_realtime_url_is_skipped_even_when_the_atlas_says_gtfs() {
431 let r = resolve(
432 r#"{"sources":[{"name":"R","transitland-atlas-id":"f-static",
433 "url-override":"https://a/gtfs-rt/trips"}]}"#,
434 ATLAS,
435 );
436 assert!(r.feeds.is_empty());
437 assert!(r.skipped[0].why.contains("realtime endpoint"));
438 }
439
440 #[test]
441 fn dedup_drops_repeats_by_name_then_by_url() {
442 let mut feeds = vec![
443 Resolved { name: "a".into(), source: "r-A".into(), url: "u1".into(), via: "x" },
444 // Same name from another region file.
445 Resolved { name: "a".into(), source: "s-A".into(), url: "u2".into(), via: "x" },
446 // Different name, same combined feed.
447 Resolved { name: "b".into(), source: "r-B".into(), url: "u1".into(), via: "x" },
448 Resolved { name: "c".into(), source: "r-C".into(), url: "u3".into(), via: "x" },
449 ];
450 dedup(&mut feeds);
451 assert_eq!(
452 feeds.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(),
453 ["a", "c"]
454 );
455 // The first of each is the one kept, so the result is order-stable.
456 assert_eq!(feeds[0].source, "r-A");
457 }
458
459 #[test]
460 fn a_registry_with_no_sources_resolves_to_nothing_without_erroring() {
461 let r = resolve("{}", ATLAS);
462 assert_eq!(r.considered, 0);
463 assert!(r.feeds.is_empty() && r.skipped.is_empty());
464 let r = resolve(r#"{"sources":[]}"#, ATLAS);
465 assert_eq!(r.considered, 0);
466 }
467
468 #[test]
469 fn the_atlas_index_covers_every_document() {
470 let docs = vec![
471 json::parse(r#"{"feeds":[{"id":"a"},{"id":"b"}]}"#).unwrap(),
472 json::parse(r#"{"feeds":[{"id":"c"}]}"#).unwrap(),
473 // A document with no feeds must not break the index.
474 json::parse(r#"{"license":{}}"#).unwrap(),
475 ];
476 let index = index_atlas(&docs);
477 assert_eq!(index.len(), 3);
478 assert!(index.contains_key("a") && index.contains_key("c"));
479 }
480}