Skip to main content

rmv_core/
service.rs

1//! The operations of the CLI and the MCP server, with the rules of RMV
2//! applied: no request without an access key, and a request is repeated
3//! only as [`retry`](crate::retry) allows.
4
5use std::fmt;
6use std::sync::{Arc, OnceLock};
7use std::time::Duration;
8
9use hafas::{ArrivalBoard, Client, DepartureBoard, JourneyDetail, LocationName, Request};
10use jiff::{Timestamp, ToSpan};
11
12use crate::config::Config;
13use crate::error::is_no_result;
14use crate::model::{
15    Attribution, Departure, DeparturesResult, FindStopResult, JourneyResult, Location, PageCursor,
16    StopMatch,
17};
18use crate::retry::{self, Policy};
19use crate::version::{self, Informed};
20use crate::{Error, agent, convert, modes, resolve, time};
21
22/// The most stops of one search.
23pub const MAX_STOPS: u32 = 20;
24/// The most departures of one search.
25pub const MAX_DEPARTURES: u32 = 100;
26/// The matches a name is chosen from.
27const RESOLVE_MATCHES: u32 = 10;
28/// How far a board looks ahead, in minutes: the most the API takes. The
29/// number of departures limits it.
30const BOARD_MINUTES: u32 = 1439;
31
32/// The current time. Replaceable for tests.
33pub type Clock = Arc<dyn Fn() -> Timestamp + Send + Sync>;
34
35/// A search for stops.
36#[derive(Debug, Clone, Default, PartialEq)]
37pub struct StopsQuery {
38    pub text: String,
39    /// Prefer stops near `(lat, lon)`.
40    pub near: Option<(f64, f64)>,
41    /// At most [`MAX_STOPS`].
42    pub count: u32,
43}
44
45/// A search for departures or arrivals.
46#[derive(Debug, Clone, Default, PartialEq, Eq)]
47pub struct DeparturesQuery {
48    /// A stop ID, or a name that names one stop.
49    pub stop: String,
50    /// `None`: now.
51    pub time: Option<Timestamp>,
52    /// How many to ask for, at most [`MAX_DEPARTURES`]. The API can return
53    /// more, and the result has them all.
54    pub count: u32,
55    pub arrivals: bool,
56    /// Only these modes, like `SUBURBAN`. Empty: all.
57    pub modes: Vec<String>,
58    /// The `later` cursor of an earlier result. It replaces `time`.
59    pub page_cursor: Option<String>,
60}
61
62/// RMV with its rules.
63#[derive(Clone)]
64pub struct Rmv {
65    pub(crate) client: Client,
66    pub(crate) policy: Policy,
67    pub(crate) delay_threshold_minutes: u32,
68    pub(crate) clock: Clock,
69    /// The first version newer than the tested one that answered.
70    pub(crate) newer_version: Arc<OnceLock<String>>,
71}
72
73impl fmt::Debug for Rmv {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        f.debug_struct("Rmv")
76            .field("client", &self.client)
77            .field("policy", &self.policy)
78            .finish_non_exhaustive()
79    }
80}
81
82impl Rmv {
83    /// A client for `config`, naming `product` (like `rmv/1.2.0`) in the
84    /// User-Agent.
85    ///
86    /// Fails with [`Error::AccessIdMissing`] without an access key: no
87    /// request is possible then.
88    pub fn new(config: &Config, product: &str) -> Result<Self, Error> {
89        let access_id = config.access_id.as_deref().ok_or(Error::AccessIdMissing)?;
90        let client = Client::builder(&config.base_url)
91            .access_id(access_id)
92            .user_agent(agent::user_agent(product))
93            .timeout(config.timeout)
94            .build()
95            .map_err(Error::from)?;
96        Ok(Self {
97            client,
98            policy: Policy {
99                retries: config.retries,
100                timeout: config.timeout,
101                delay: retry::DEFAULT_DELAY,
102            },
103            delay_threshold_minutes: config.delay_threshold_minutes,
104            clock: Arc::new(Timestamp::now),
105            newer_version: Arc::default(),
106        })
107    }
108
109    /// Uses `clock` for the current time.
110    #[must_use]
111    pub fn with_clock(mut self, clock: Clock) -> Self {
112        self.clock = clock;
113        self
114    }
115
116    /// Waits `delay` before the first repetition instead of
117    /// [`retry::DEFAULT_DELAY`].
118    #[must_use]
119    pub fn with_retry_delay(mut self, delay: Duration) -> Self {
120        self.policy.delay = delay;
121        self
122    }
123
124    /// The version of the API, like `2.60`, if one newer than
125    /// [`version::TESTED_VERSION`] has answered: its responses may hold data
126    /// that this version of `rmv` does not know. Callers warn about it once.
127    pub fn newer_version(&self) -> Option<&str> {
128        self.newer_version.get().map(String::as_str)
129    }
130
131    /// Notes the version of `response`.
132    fn noted<T: Informed>(&self, response: T) -> T {
133        if let Some(newer) = version::newer(response.info()) {
134            let _ = self.newer_version.set(newer);
135        }
136        response
137    }
138
139    /// One request, repeated as the policy allows.
140    pub(crate) async fn call<R>(&self, request: &R) -> Result<R::Response, Error>
141    where
142        R: Request,
143        R::Response: Informed,
144    {
145        let response = retry::run(&self.policy, || self.client.send(request)).await?;
146        Ok(self.noted(response))
147    }
148
149    /// Like [`Rmv::call`], with `None` when the API found nothing.
150    pub(crate) async fn call_or_none<R>(&self, request: &R) -> Result<Option<R::Response>, Error>
151    where
152        R: Request,
153        R::Response: Informed,
154    {
155        match retry::run(&self.policy, || self.client.send(request)).await {
156            Ok(response) => Ok(Some(self.noted(response))),
157            Err(retry::Failure::Hafas(error)) if is_no_result(&error) => Ok(None),
158            Err(failure) => Err(failure.into()),
159        }
160    }
161
162    /// Stops by name.
163    pub async fn find_stops(&self, query: &StopsQuery) -> Result<FindStopResult, Error> {
164        let request = LocationName {
165            max_no: Some(query.count.clamp(1, MAX_STOPS)),
166            kind: Some("S".to_owned()),
167            near: query.near,
168            ..LocationName::new(query.text.trim())
169        };
170        let list = self.call_or_none(&request).await?.unwrap_or_default();
171        Ok(FindStopResult {
172            query: query.text.clone(),
173            stops: list.stops().map(StopMatch::from).collect(),
174            attribution: Attribution::default(),
175            warnings: Vec::new(),
176        })
177    }
178
179    /// The stop for an ID or a name: its ID and, for a name, its name.
180    pub async fn resolve_stop(&self, input: &str) -> Result<(String, Option<String>), Error> {
181        let input = input.trim();
182        if resolve::is_stop_id(input) {
183            return Ok((input.to_owned(), None));
184        }
185        let not_found = || Error::StopNotFound {
186            query: input.to_owned(),
187        };
188        if input.is_empty() {
189            return Err(not_found());
190        }
191        let request = LocationName {
192            max_no: Some(RESOLVE_MATCHES),
193            kind: Some("S".to_owned()),
194            ..LocationName::new(input)
195        };
196        let list = self.call_or_none(&request).await?.ok_or_else(not_found)?;
197        let stops: Vec<&hafas::StopLocation> = list.stops().collect();
198        let stop = resolve::choose(input, &stops)?;
199        Ok((convert::stop_id(stop), Some(stop.name.clone())))
200    }
201
202    /// Departures or arrivals at a stop.
203    pub async fn departures(&self, query: &DeparturesQuery) -> Result<DeparturesResult, Error> {
204        let products = modes::products(&query.modes)?;
205        let start = match query.page_cursor.as_deref() {
206            Some(cursor) => {
207                Some(
208                    cursor
209                        .trim()
210                        .parse::<Timestamp>()
211                        .map_err(|_| Error::BadRequest {
212                            message: format!("{cursor:?} is not a page cursor of rmv"),
213                        })?,
214                )
215            }
216            None => query.time,
217        };
218        let (stop_id, stop_name) = self.resolve_stop(&query.stop).await?;
219        let (date, time) = start.map(time::request).unzip();
220        let max_journeys = Some(query.count.clamp(1, MAX_DEPARTURES));
221        let (departures, info): (Vec<Departure>, _) = if query.arrivals {
222            let request = ArrivalBoard {
223                date,
224                time,
225                duration: Some(BOARD_MINUTES),
226                max_journeys,
227                products,
228                ..ArrivalBoard::new(stop_id.clone())
229            };
230            let list = self.call_or_none(&request).await?.unwrap_or_default();
231            let departures = list
232                .arrivals
233                .iter()
234                .map(|arrival| Departure::new(&arrival.event, None, arrival.origin.as_deref()))
235                .collect();
236            (departures, list.info)
237        } else {
238            let request = DepartureBoard {
239                date,
240                time,
241                duration: Some(BOARD_MINUTES),
242                max_journeys,
243                products,
244                ..DepartureBoard::new(stop_id.clone())
245            };
246            let list = self.call_or_none(&request).await?.unwrap_or_default();
247            let departures = list
248                .departures
249                .iter()
250                .map(|departure| {
251                    Departure::new(&departure.event, departure.direction.as_deref(), None)
252                })
253                .collect();
254            (departures, list.info)
255        };
256        Ok(DeparturesResult {
257            stop: board_stop(&departures, stop_id, stop_name),
258            arrivals: query.arrivals,
259            page_cursor: PageCursor {
260                earlier: None,
261                later: later(&departures),
262            },
263            departures,
264            realtime_as_of: time::plan_rt(info.plan_rt_ts.as_deref()),
265            attribution: Attribution::default(),
266            warnings: Vec::new(),
267        })
268    }
269
270    /// A trip with all its stops, by the `trip_id` of a departure or leg.
271    pub async fn journey(&self, trip_id: &str) -> Result<JourneyResult, Error> {
272        let journey = self.call(&JourneyDetail::new(trip_id.trim())).await?;
273        Ok(JourneyResult::new(trip_id.trim(), &journey, Vec::new()))
274    }
275}
276
277/// The stop of a board: as the first departure names it, else as resolved.
278fn board_stop(departures: &[Departure], id: String, name: Option<String>) -> Location {
279    match departures.first() {
280        Some(first) => Location {
281            id: first.stop.id.clone().or(Some(id)),
282            name: first.stop.name.clone(),
283            dhid: first.stop.dhid.clone(),
284        },
285        None => Location {
286            name: name.unwrap_or_else(|| id.clone()),
287            id: Some(id),
288            dhid: None,
289        },
290    }
291}
292
293/// The cursor after a board: a minute after its last scheduled time. A
294/// board always has every departure of its last minute, so none is lost.
295fn later(departures: &[Departure]) -> Option<String> {
296    let last = departures
297        .iter()
298        .filter_map(|departure| departure.stop.time.scheduled.parse::<Timestamp>().ok())
299        .max()?;
300    last.checked_add(1.minute()).ok().map(time::format)
301}
302
303#[cfg(test)]
304mod tests {
305    use super::*;
306
307    #[test]
308    fn an_empty_board_has_no_later_page() {
309        assert_eq!(later(&[]), None);
310        let stop = board_stop(&[], "3000010".into(), None);
311        assert_eq!(stop.name, "3000010");
312        assert_eq!(stop.id.as_deref(), Some("3000010"));
313    }
314}