1use std::fmt;
13use std::sync::Arc;
14use std::time::Duration;
15
16use jiff::Timestamp;
17use jiff::tz::TimeZone;
18use motis::{Client, Geocode, LocationType, Mode, Plan, RealtimeMode, Request, Stoptimes, Trip};
19
20use crate::cache::{self, Cache};
21use crate::config::Config;
22use crate::model::{
23 Attribution, Connection, Departure, DeparturesResult, FindStopResult, JourneyResult, Location,
24 PageCursor, StopMatch, TripResult, UsageSummary,
25};
26use crate::time::{self, QueryTime};
27use crate::usage::{Endpoint, Usage};
28use crate::{Error, agent, resolve, status};
29
30pub const MAX_CONNECTIONS: u32 = 20;
32pub const MAX_DEPARTURES: u32 = 100;
34pub const MAX_STOPS: u32 = 20;
36const MIN_ARRIVE_BY: u32 = 3;
39const RESOLVE_MATCHES: u32 = 10;
41const ZONE_TTL: Duration = Duration::from_secs(60 * 60);
44
45pub type Clock = Arc<dyn Fn() -> Timestamp + Send + Sync>;
47
48pub trait Call: Request {
50 const ENDPOINT: Endpoint;
51}
52
53impl Call for Geocode {
54 const ENDPOINT: Endpoint = Endpoint::Geocode;
55}
56impl Call for motis::ReverseGeocode {
57 const ENDPOINT: Endpoint = Endpoint::ReverseGeocode;
58}
59impl Call for Plan {
60 const ENDPOINT: Endpoint = Endpoint::Plan;
61}
62impl Call for Stoptimes {
63 const ENDPOINT: Endpoint = Endpoint::Stoptimes;
64}
65impl Call for Trip {
66 const ENDPOINT: Endpoint = Endpoint::Trip;
67}
68
69#[derive(Debug, Clone, Default, PartialEq)]
71pub struct StopsQuery {
72 pub text: String,
73 pub near: Option<(f64, f64)>,
75 pub count: u32,
77}
78
79#[derive(Debug, Clone, Default, PartialEq, Eq)]
81pub struct DeparturesQuery {
82 pub stop: String,
84 pub time: Option<QueryTime>,
86 pub count: u32,
89 pub arrivals: bool,
90 pub modes: Vec<Mode>,
92 pub page_cursor: Option<String>,
93}
94
95#[derive(Debug, Clone, Default, PartialEq, Eq)]
97#[allow(clippy::struct_excessive_bools, reason = "independent options")]
98pub struct TripQuery {
99 pub from: String,
101 pub to: String,
102 pub time: Option<QueryTime>,
105 pub arrive_by: bool,
108 pub count: u32,
112 pub modes: Vec<Mode>,
114 pub max_transfers: Option<u32>,
115 pub page_cursor: Option<String>,
116 pub realtime_routing: bool,
119}
120
121#[derive(Clone)]
123pub struct Transitous {
124 client: Client,
125 cache: Cache,
126 usage: Usage,
127 delay_threshold_minutes: u32,
128 clock: Clock,
129 zone: TimeZone,
130}
131
132impl fmt::Debug for Transitous {
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 f.debug_struct("Transitous")
135 .field("client", &self.client)
136 .field("cache", &self.cache)
137 .field("usage", &self.usage)
138 .finish_non_exhaustive()
139 }
140}
141
142impl Transitous {
143 pub fn new(config: &Config, product: &str) -> Result<Self, Error> {
149 let user_agent = agent::user_agent(product, config.contact.as_deref())?;
150 let client = Client::builder(&config.base_url)
151 .user_agent(user_agent)
152 .timeout(config.timeout)
153 .build()?;
154 Ok(Self {
155 client,
156 cache: Cache::new(config.cache_dir.clone()),
157 usage: Usage::new(config.state_dir.as_deref(), config.plan_daily_limit),
158 delay_threshold_minutes: config.delay_threshold_minutes,
159 clock: Arc::new(Timestamp::now),
160 zone: TimeZone::system(),
161 })
162 }
163
164 #[must_use]
167 pub fn with_zone(mut self, zone: TimeZone) -> Self {
168 self.zone = zone;
169 self
170 }
171
172 #[must_use]
174 pub fn with_clock(mut self, clock: Clock) -> Self {
175 self.clock = clock;
176 self
177 }
178
179 pub fn usage(&self) -> &Usage {
181 &self.usage
182 }
183
184 pub fn usage_summary(&self) -> Result<UsageSummary, Error> {
186 self.usage.summary((self.clock)())
187 }
188
189 async fn call<R: Call>(
191 &self,
192 request: &R,
193 warnings: &mut Vec<String>,
194 ) -> Result<R::Response, Error> {
195 let key = self.client.url(request).to_string();
196 let now = (self.clock)();
197 let cached = self
198 .cache
199 .get(&key, cache::ttl(R::ENDPOINT), now)
200 .and_then(|body| Client::decode::<R>(&body).ok());
201 if let Some(response) = cached {
202 return Ok(response);
203 }
204 warnings.extend(self.usage.admit(R::ENDPOINT, now)?);
205 let body = self.client.fetch(request).await?;
206 let response = Client::decode::<R>(&body)?;
207 self.cache.put(&key, &body, now);
208 Ok(response)
209 }
210
211 pub async fn find_stops(&self, query: &StopsQuery) -> Result<FindStopResult, Error> {
213 let mut warnings = Vec::new();
214 let request = Geocode {
215 types: vec![LocationType::Stop],
216 place: query.near.map(|(lat, lon)| format!("{lat},{lon}")),
217 num_results: Some(query.count.clamp(1, MAX_STOPS)),
218 ..Geocode::new(query.text.clone())
219 };
220 let matches = self.call(&request, &mut warnings).await?;
221 Ok(FindStopResult {
222 query: query.text.clone(),
223 stops: matches
224 .iter()
225 .filter(|found| found.kind == LocationType::Stop)
226 .map(StopMatch::from)
227 .collect(),
228 attribution: Attribution::default(),
229 warnings,
230 })
231 }
232
233 pub async fn resolve_stop(
235 &self,
236 input: &str,
237 warnings: &mut Vec<String>,
238 ) -> Result<String, Error> {
239 Ok(self.resolve_stop_zone(input, warnings).await?.0)
240 }
241
242 async fn resolve_stop_zone(
245 &self,
246 input: &str,
247 warnings: &mut Vec<String>,
248 ) -> Result<(String, Option<String>), Error> {
249 let input = input.trim();
250 if resolve::is_stop_id(input) {
251 return Ok((input.to_owned(), None));
252 }
253 if input.is_empty() {
254 return Err(Error::StopNotFound {
255 query: input.to_owned(),
256 });
257 }
258 let request = Geocode {
259 types: vec![LocationType::Stop],
260 num_results: Some(RESOLVE_MATCHES),
261 ..Geocode::new(input)
262 };
263 let matches = self.call(&request, warnings).await?;
264 let chosen = resolve::choose(input, &matches)?;
265 Ok((chosen.id.clone(), chosen.tz.clone()))
266 }
267
268 async fn resolve_place(
271 &self,
272 input: &str,
273 warnings: &mut Vec<String>,
274 ) -> Result<(String, Option<String>), Error> {
275 match resolve::coordinates(input) {
276 Some((lat, lon)) => Ok((format!("{lat},{lon}"), None)),
277 None => self.resolve_stop_zone(input, warnings).await,
278 }
279 }
280
281 fn zone(&self, place: &str, told: Option<&str>, now: Timestamp) -> TimeZone {
284 let known = || {
285 let body = self.cache.get(&zone_key(place), ZONE_TTL, now)?;
286 time::zone(Some(&String::from_utf8(body).ok()?))
287 };
288 time::zone(told)
289 .or_else(known)
290 .unwrap_or_else(|| self.zone.clone())
291 }
292
293 async fn call_at<R: Call>(
298 &self,
299 mut request: R,
300 local: Option<Local<'_>>,
301 retime: impl Fn(&mut R, Timestamp),
302 zone_of: impl Fn(&R::Response) -> Option<&str>,
303 warnings: &mut Vec<String>,
304 ) -> Result<(R, R::Response), Error> {
305 let response = self.call(&request, warnings).await?;
306 let Some(local) = local else {
307 return Ok((request, response));
308 };
309 let told = zone_of(&response).and_then(|name| Some((name, time::zone(Some(name))?)));
310 let Some((name, actual)) = told.filter(|(_, actual)| *actual != local.zone) else {
311 return Ok((request, response));
312 };
313 let now = (self.clock)();
314 self.cache.put(&zone_key(local.place), name.as_bytes(), now);
315 let instant = local.time.in_zone(&actual, now).map_err(bad_time)?;
316 if Some(instant) == local.time.in_zone(&local.zone, now).ok() {
317 return Ok((request, response));
318 }
319 retime(&mut request, instant);
320 let response = self.call(&request, warnings).await?;
321 Ok((request, response))
322 }
323
324 pub async fn departures(&self, query: &DeparturesQuery) -> Result<DeparturesResult, Error> {
326 let mut warnings = Vec::new();
327 let (stop_id, told) = self.resolve_stop_zone(&query.stop, &mut warnings).await?;
328 let now = (self.clock)();
329 let zone = self.zone(&stop_id, told.as_deref(), now);
330 let time = at(query.time, &zone, now)?;
331 let local = Local::new(query.time, &stop_id, zone, query.page_cursor.is_none());
332 let request = Stoptimes {
333 time,
334 arrive_by: Some(query.arrivals),
335 n: Some(query.count.clamp(1, MAX_DEPARTURES)),
336 mode: query.modes.clone(),
337 page_cursor: query.page_cursor.clone(),
338 with_alerts: Some(true),
339 ..Stoptimes::new(stop_id.clone())
340 };
341 let (_, response) = self
342 .call_at(
343 request,
344 local,
345 |request, time| request.time = Some(time),
346 |response| response.place.tz.as_deref(),
347 &mut warnings,
348 )
349 .await?;
350 let mut stop = Location::from(&response.place);
351 stop.id.get_or_insert(stop_id);
352 Ok(DeparturesResult {
353 stop,
354 arrivals: query.arrivals,
355 departures: response
356 .stop_times
357 .iter()
358 .map(|stop_time| Departure::new(stop_time, query.arrivals))
359 .collect(),
360 page_cursor: PageCursor::new(
361 &response.previous_page_cursor,
362 &response.next_page_cursor,
363 ),
364 attribution: Attribution::default(),
365 warnings,
366 })
367 }
368
369 pub async fn trip(&self, query: &TripQuery) -> Result<TripResult, Error> {
375 let mut warnings = Vec::new();
376 let (from, from_zone) = self.resolve_place(&query.from, &mut warnings).await?;
377 let (to, to_zone) = self.resolve_place(&query.to, &mut warnings).await?;
378 let count = query.count.clamp(1, MAX_CONNECTIONS);
379 let wanted = if query.arrive_by {
380 count.max(MIN_ARRIVE_BY)
381 } else {
382 count
383 };
384 let now = (self.clock)();
385 let (place, told) = if query.arrive_by {
386 (&to, to_zone)
387 } else {
388 (&from, from_zone)
389 };
390 let zone = self.zone(place, told.as_deref(), now);
391 let time = at(query.time, &zone, now)?;
392 let local = Local::new(query.time, place, zone, query.page_cursor.is_none());
393 let arrive_by = query.arrive_by;
394 let request = Plan {
395 time: time.or(query.arrive_by.then_some(now)),
396 arrive_by: Some(query.arrive_by),
397 num_itineraries: Some(wanted),
398 page_cursor: query.page_cursor.clone(),
399 transit_modes: query.modes.clone(),
400 max_transfers: query.max_transfers,
401 realtime_mode: Some(if query.realtime_routing {
402 RealtimeMode::Realtime
403 } else {
404 RealtimeMode::RealtimeAnnotationOnly
405 }),
406 ..Plan::new(from.clone(), to.clone())
407 };
408 let (request, response) = self
409 .call_at(
410 request,
411 local,
412 |request, time| request.time = Some(time),
413 |response| {
414 let place = if arrive_by {
415 &response.to
416 } else {
417 &response.from
418 };
419 place.tz.as_deref()
420 },
421 &mut warnings,
422 )
423 .await?;
424 let mut itineraries = response.itineraries;
427 add_new(&mut itineraries, response.direct);
428 let mut earlier = response.previous_page_cursor;
429 let later = response.next_page_cursor;
430 let short = itineraries.len() < count as usize;
431 if query.arrive_by && query.page_cursor.is_none() && short && !earlier.is_empty() {
432 let previous = Plan {
433 page_cursor: Some(earlier.clone()),
434 ..request
435 };
436 match self.call(&previous, &mut warnings).await {
437 Ok(page) => {
438 earlier = page.previous_page_cursor;
439 add_new(&mut itineraries, page.itineraries);
440 }
441 Err(error) => warnings.push(format!("no earlier connections: {error}")),
442 }
443 }
444 itineraries.sort_by_key(departure);
445 let now = (self.clock)();
446 Ok(TripResult {
447 from: Location::from(&response.from),
448 to: Location::from(&response.to),
449 connections: itineraries
450 .iter()
451 .map(|itinerary| {
452 let evaluation = status::evaluate(itinerary, now, self.delay_threshold_minutes);
453 Connection::new(itinerary, evaluation)
454 })
455 .collect(),
456 page_cursor: PageCursor::new(&earlier, &later),
457 attribution: Attribution::default(),
458 warnings,
459 })
460 }
461
462 pub async fn journey(&self, trip_id: &str) -> Result<JourneyResult, Error> {
464 let mut warnings = Vec::new();
465 let itinerary = self.call(&Trip::new(trip_id), &mut warnings).await?;
466 Ok(JourneyResult::new(trip_id, &itinerary, warnings))
467 }
468}
469
470fn departure(itinerary: &motis::Itinerary) -> Timestamp {
473 itinerary
474 .legs
475 .first()
476 .map_or(itinerary.start_time, |leg| leg.scheduled_start_time)
477}
478
479fn add_new(known: &mut Vec<motis::Itinerary>, page: Vec<motis::Itinerary>) {
482 for itinerary in page {
483 if !known.iter().any(|other| same(other, &itinerary)) {
484 known.push(itinerary);
485 }
486 }
487}
488
489fn same(a: &motis::Itinerary, b: &motis::Itinerary) -> bool {
490 if !a.id.is_empty() && !b.id.is_empty() {
491 return a.id == b.id;
492 }
493 let trips = |it: &motis::Itinerary| -> Vec<(Option<String>, Timestamp)> {
494 it.legs
495 .iter()
496 .map(|leg| (leg.trip_id.clone(), leg.scheduled_start_time))
497 .collect()
498 };
499 trips(a) == trips(b)
500}
501
502struct Local<'a> {
504 time: QueryTime,
505 place: &'a str,
506 zone: TimeZone,
507}
508
509impl<'a> Local<'a> {
510 fn new(time: Option<QueryTime>, place: &'a str, zone: TimeZone, first: bool) -> Option<Self> {
513 let time = time.filter(|time| first && time.is_local())?;
514 Some(Self { time, place, zone })
515 }
516}
517
518fn at(
520 time: Option<QueryTime>,
521 zone: &TimeZone,
522 now: Timestamp,
523) -> Result<Option<Timestamp>, Error> {
524 time.map(|time| time.in_zone(zone, now))
525 .transpose()
526 .map_err(bad_time)
527}
528
529fn bad_time(message: String) -> Error {
530 Error::BadRequest { message }
531}
532
533fn zone_key(place: &str) -> String {
535 format!("zone:{place}")
536}
537
538#[cfg(test)]
539mod tests {
540 use super::*;
541
542 #[test]
543 fn tells_connections_apart() {
544 let leg = |trip: &str, minute: i64| motis::Leg {
545 trip_id: Some(trip.into()),
546 scheduled_start_time: Timestamp::from_second(minute * 60).unwrap(),
547 ..motis::Leg::default()
548 };
549 let with = |id: &str, legs| motis::Itinerary {
550 id: id.into(),
551 legs,
552 ..motis::Itinerary::default()
553 };
554 assert!(same(&with("a", vec![]), &with("a", vec![leg("x", 1)])));
555 assert!(!same(&with("a", vec![]), &with("b", vec![])));
556 assert!(same(
557 &with("", vec![leg("x", 1)]),
558 &with("", vec![leg("x", 1)])
559 ));
560 assert!(!same(
561 &with("", vec![leg("x", 1)]),
562 &with("a", vec![leg("x", 2)])
563 ));
564 assert_eq!(departure(&with("", vec![])), Timestamp::default());
565 let mut known = vec![with("a", vec![]), with("b", vec![])];
566 add_new(&mut known, vec![with("b", vec![]), with("c", vec![])]);
567 let ids: Vec<&str> = known.iter().map(|i| i.id.as_str()).collect();
568 assert_eq!(ids, ["a", "b", "c"]);
569 }
570}