Skip to main content

transitous_core/
service.rs

1//! The operations of the CLI and the MCP server, with the usage rules
2//! applied: a contact in every request, the cache first, then the usage
3//! counter, then one request, never a retry.
4//!
5//! A local time like `07:50` is the time at the stop, in its time zone, like
6//! the times of the results. A stop given by name tells its zone in the name
7//! search. For a stop given by ID, the zone of an earlier answer or of the
8//! process is a guess; if the answer names another zone in which the time is
9//! another instant, the request is sent once more, and the zone is kept for
10//! an hour.
11
12use 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
30/// The most connections of one search.
31pub const MAX_CONNECTIONS: u32 = 20;
32/// The most departures of one search.
33pub const MAX_DEPARTURES: u32 = 100;
34/// The most stops of one search.
35pub const MAX_STOPS: u32 = 20;
36/// The connections an arrive-by search asks for at least, so the earlier
37/// ones are there to switch to.
38const MIN_ARRIVE_BY: u32 = 3;
39/// The geocoding matches a name is chosen from.
40const RESOLVE_MATCHES: u32 = 10;
41/// How long the time zone of a stop from an answer keeps, so that a local
42/// time at a stop given by ID needs a second request at most once an hour.
43const ZONE_TTL: Duration = Duration::from_secs(60 * 60);
44
45/// The current time. Replaceable for tests.
46pub type Clock = Arc<dyn Fn() -> Timestamp + Send + Sync>;
47
48/// A request type of the API with its endpoint.
49pub 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/// A search for stops.
70#[derive(Debug, Clone, Default, PartialEq)]
71pub struct StopsQuery {
72    pub text: String,
73    /// Prefer stops near `(lat, lon)`.
74    pub near: Option<(f64, f64)>,
75    /// At most [`MAX_STOPS`].
76    pub count: u32,
77}
78
79/// A search for departures or arrivals.
80#[derive(Debug, Clone, Default, PartialEq, Eq)]
81pub struct DeparturesQuery {
82    /// A stop ID, or a name that names one stop.
83    pub stop: String,
84    /// `None`: now. A local time is the time at the stop.
85    pub time: Option<QueryTime>,
86    /// How many to ask for, at most [`MAX_DEPARTURES`]. The API can return
87    /// more, and the result has them all.
88    pub count: u32,
89    pub arrivals: bool,
90    /// Only these modes. Empty: all.
91    pub modes: Vec<Mode>,
92    pub page_cursor: Option<String>,
93}
94
95/// A search for connections.
96#[derive(Debug, Clone, Default, PartialEq, Eq)]
97#[allow(clippy::struct_excessive_bools, reason = "independent options")]
98pub struct TripQuery {
99    /// A stop ID, a name that names one stop, or `LAT,LON`.
100    pub from: String,
101    pub to: String,
102    /// `None`: now. A local time is the time at `from`, or at `to` with
103    /// `arrive_by`.
104    pub time: Option<QueryTime>,
105    /// Whether `time` is the latest arrival rather than the earliest
106    /// departure.
107    pub arrive_by: bool,
108    /// How many connections to ask for, at most [`MAX_CONNECTIONS`]. The
109    /// result has all the API returns, which can be more: the page cursors
110    /// continue after the whole page, so nothing is dropped.
111    pub count: u32,
112    /// Only these transit modes. Empty: all.
113    pub modes: Vec<Mode>,
114    pub max_transfers: Option<u32>,
115    pub page_cursor: Option<String>,
116    /// Route on the realtime timetable: cancelled trips and missed transfers
117    /// drop out instead of showing with their status.
118    pub realtime_routing: bool,
119}
120
121/// Transitous with the usage rules.
122#[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    /// A client for `config`, naming `product` (like `transitous/1.2.0`) in
144    /// the User-Agent.
145    ///
146    /// Fails with [`Error::ContactMissing`] without a contact: no request is
147    /// possible then.
148    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    /// Reads local times in `zone` at places whose time zone is not known
165    /// before the request, instead of in the zone of the process.
166    #[must_use]
167    pub fn with_zone(mut self, zone: TimeZone) -> Self {
168        self.zone = zone;
169        self
170    }
171
172    /// Uses `clock` for the current time.
173    #[must_use]
174    pub fn with_clock(mut self, clock: Clock) -> Self {
175        self.clock = clock;
176        self
177    }
178
179    /// The usage counter.
180    pub fn usage(&self) -> &Usage {
181        &self.usage
182    }
183
184    /// The requests of the last 24 hours.
185    pub fn usage_summary(&self) -> Result<UsageSummary, Error> {
186        self.usage.summary((self.clock)())
187    }
188
189    /// One request: from the cache, or counted and sent once.
190    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    /// Stops by name.
212    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    /// The stop ID for an ID or a name.
234    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    /// The stop ID for an ID or a name, with the time zone of the stop if
243    /// the name search tells it.
244    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    /// A place for the routing: coordinates as they are, else a stop, with
269    /// the time zone if the name search tells it.
270    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    /// The time zone of `place`: the one the name search told, else the one
282    /// an earlier answer told, else the one of this client.
283    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    /// Sends `request` at `time`, a local time read in the zone `local.zone`
294    /// of the place. If the answer names another zone for the place, in which
295    /// the time is another instant, it sends the request once more at that
296    /// instant and keeps the zone for the place.
297    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    /// Departures or arrivals at a stop.
325    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    /// Connections between two places, each with its status.
370    ///
371    /// An arrive-by search returns the connections that arrive last before
372    /// the time, so the earlier ones are there to switch to. If one page
373    /// has fewer than `count`, it asks once more for the page before.
374    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        // Walking can beat every ride: the API then returns it as a direct
425        // route and leaves out the slower rides.
426        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    /// A trip with all its stops.
463    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
470/// The departure of the first leg, by the schedule: the order of the
471/// timetable, which delays do not change.
472fn departure(itinerary: &motis::Itinerary) -> Timestamp {
473    itinerary
474        .legs
475        .first()
476        .map_or(itinerary.start_time, |leg| leg.scheduled_start_time)
477}
478
479/// Whether two itineraries are the same connection.
480/// Adds the connections of `page` that `known` does not have yet.
481fn 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
502/// A local time of a search and the place and zone it was read in.
503struct Local<'a> {
504    time: QueryTime,
505    place: &'a str,
506    zone: TimeZone,
507}
508
509impl<'a> Local<'a> {
510    /// `Some` for a local time of a first page: later pages continue from
511    /// their cursor.
512    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
518/// The instant of `time` in `zone`.
519fn 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
533/// The cache key of the time zone of `place`.
534fn 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}