rmv-core 1.0.0

Configuration, retries, stop resolution and connection status for the RMV API
Documentation
//! The operations of the CLI and the MCP server, with the rules of RMV
//! applied: no request without an access key, and a request is repeated
//! only as [`retry`](crate::retry) allows.

use std::fmt;
use std::sync::{Arc, OnceLock};
use std::time::Duration;

use hafas::{ArrivalBoard, Client, DepartureBoard, JourneyDetail, LocationName, Request};
use jiff::{Timestamp, ToSpan};

use crate::config::Config;
use crate::error::is_no_result;
use crate::model::{
    Attribution, Departure, DeparturesResult, FindStopResult, JourneyResult, Location, PageCursor,
    StopMatch,
};
use crate::retry::{self, Policy};
use crate::version::{self, Informed};
use crate::{Error, agent, convert, modes, resolve, time};

/// The most stops of one search.
pub const MAX_STOPS: u32 = 20;
/// The most departures of one search.
pub const MAX_DEPARTURES: u32 = 100;
/// The matches a name is chosen from.
const RESOLVE_MATCHES: u32 = 10;
/// How far a board looks ahead, in minutes: the most the API takes. The
/// number of departures limits it.
const BOARD_MINUTES: u32 = 1439;

/// The current time. Replaceable for tests.
pub type Clock = Arc<dyn Fn() -> Timestamp + Send + Sync>;

/// A search for stops.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct StopsQuery {
    pub text: String,
    /// Prefer stops near `(lat, lon)`.
    pub near: Option<(f64, f64)>,
    /// At most [`MAX_STOPS`].
    pub count: u32,
}

/// A search for departures or arrivals.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DeparturesQuery {
    /// A stop ID, or a name that names one stop.
    pub stop: String,
    /// `None`: now.
    pub time: Option<Timestamp>,
    /// How many to ask for, at most [`MAX_DEPARTURES`]. The API can return
    /// more, and the result has them all.
    pub count: u32,
    pub arrivals: bool,
    /// Only these modes, like `SUBURBAN`. Empty: all.
    pub modes: Vec<String>,
    /// The `later` cursor of an earlier result. It replaces `time`.
    pub page_cursor: Option<String>,
}

/// RMV with its rules.
#[derive(Clone)]
pub struct Rmv {
    pub(crate) client: Client,
    pub(crate) policy: Policy,
    pub(crate) delay_threshold_minutes: u32,
    pub(crate) clock: Clock,
    /// The first version newer than the tested one that answered.
    pub(crate) newer_version: Arc<OnceLock<String>>,
}

impl fmt::Debug for Rmv {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Rmv")
            .field("client", &self.client)
            .field("policy", &self.policy)
            .finish_non_exhaustive()
    }
}

impl Rmv {
    /// A client for `config`, naming `product` (like `rmv/1.2.0`) in the
    /// User-Agent.
    ///
    /// Fails with [`Error::AccessIdMissing`] without an access key: no
    /// request is possible then.
    pub fn new(config: &Config, product: &str) -> Result<Self, Error> {
        let access_id = config.access_id.as_deref().ok_or(Error::AccessIdMissing)?;
        let client = Client::builder(&config.base_url)
            .access_id(access_id)
            .user_agent(agent::user_agent(product))
            .timeout(config.timeout)
            .build()
            .map_err(Error::from)?;
        Ok(Self {
            client,
            policy: Policy {
                retries: config.retries,
                timeout: config.timeout,
                delay: retry::DEFAULT_DELAY,
            },
            delay_threshold_minutes: config.delay_threshold_minutes,
            clock: Arc::new(Timestamp::now),
            newer_version: Arc::default(),
        })
    }

    /// Uses `clock` for the current time.
    #[must_use]
    pub fn with_clock(mut self, clock: Clock) -> Self {
        self.clock = clock;
        self
    }

    /// Waits `delay` before the first repetition instead of
    /// [`retry::DEFAULT_DELAY`].
    #[must_use]
    pub fn with_retry_delay(mut self, delay: Duration) -> Self {
        self.policy.delay = delay;
        self
    }

    /// The version of the API, like `2.60`, if one newer than
    /// [`version::TESTED_VERSION`] has answered: its responses may hold data
    /// that this version of `rmv` does not know. Callers warn about it once.
    pub fn newer_version(&self) -> Option<&str> {
        self.newer_version.get().map(String::as_str)
    }

    /// Notes the version of `response`.
    fn noted<T: Informed>(&self, response: T) -> T {
        if let Some(newer) = version::newer(response.info()) {
            let _ = self.newer_version.set(newer);
        }
        response
    }

    /// One request, repeated as the policy allows.
    pub(crate) async fn call<R>(&self, request: &R) -> Result<R::Response, Error>
    where
        R: Request,
        R::Response: Informed,
    {
        let response = retry::run(&self.policy, || self.client.send(request)).await?;
        Ok(self.noted(response))
    }

    /// Like [`Rmv::call`], with `None` when the API found nothing.
    pub(crate) async fn call_or_none<R>(&self, request: &R) -> Result<Option<R::Response>, Error>
    where
        R: Request,
        R::Response: Informed,
    {
        match retry::run(&self.policy, || self.client.send(request)).await {
            Ok(response) => Ok(Some(self.noted(response))),
            Err(retry::Failure::Hafas(error)) if is_no_result(&error) => Ok(None),
            Err(failure) => Err(failure.into()),
        }
    }

    /// Stops by name.
    pub async fn find_stops(&self, query: &StopsQuery) -> Result<FindStopResult, Error> {
        let request = LocationName {
            max_no: Some(query.count.clamp(1, MAX_STOPS)),
            kind: Some("S".to_owned()),
            near: query.near,
            ..LocationName::new(query.text.trim())
        };
        let list = self.call_or_none(&request).await?.unwrap_or_default();
        Ok(FindStopResult {
            query: query.text.clone(),
            stops: list.stops().map(StopMatch::from).collect(),
            attribution: Attribution::default(),
            warnings: Vec::new(),
        })
    }

    /// The stop for an ID or a name: its ID and, for a name, its name.
    pub async fn resolve_stop(&self, input: &str) -> Result<(String, Option<String>), Error> {
        let input = input.trim();
        if resolve::is_stop_id(input) {
            return Ok((input.to_owned(), None));
        }
        let not_found = || Error::StopNotFound {
            query: input.to_owned(),
        };
        if input.is_empty() {
            return Err(not_found());
        }
        let request = LocationName {
            max_no: Some(RESOLVE_MATCHES),
            kind: Some("S".to_owned()),
            ..LocationName::new(input)
        };
        let list = self.call_or_none(&request).await?.ok_or_else(not_found)?;
        let stops: Vec<&hafas::StopLocation> = list.stops().collect();
        let stop = resolve::choose(input, &stops)?;
        Ok((convert::stop_id(stop), Some(stop.name.clone())))
    }

    /// Departures or arrivals at a stop.
    pub async fn departures(&self, query: &DeparturesQuery) -> Result<DeparturesResult, Error> {
        let products = modes::products(&query.modes)?;
        let start = match query.page_cursor.as_deref() {
            Some(cursor) => {
                Some(
                    cursor
                        .trim()
                        .parse::<Timestamp>()
                        .map_err(|_| Error::BadRequest {
                            message: format!("{cursor:?} is not a page cursor of rmv"),
                        })?,
                )
            }
            None => query.time,
        };
        let (stop_id, stop_name) = self.resolve_stop(&query.stop).await?;
        let (date, time) = start.map(time::request).unzip();
        let max_journeys = Some(query.count.clamp(1, MAX_DEPARTURES));
        let (departures, info): (Vec<Departure>, _) = if query.arrivals {
            let request = ArrivalBoard {
                date,
                time,
                duration: Some(BOARD_MINUTES),
                max_journeys,
                products,
                ..ArrivalBoard::new(stop_id.clone())
            };
            let list = self.call_or_none(&request).await?.unwrap_or_default();
            let departures = list
                .arrivals
                .iter()
                .map(|arrival| Departure::new(&arrival.event, None, arrival.origin.as_deref()))
                .collect();
            (departures, list.info)
        } else {
            let request = DepartureBoard {
                date,
                time,
                duration: Some(BOARD_MINUTES),
                max_journeys,
                products,
                ..DepartureBoard::new(stop_id.clone())
            };
            let list = self.call_or_none(&request).await?.unwrap_or_default();
            let departures = list
                .departures
                .iter()
                .map(|departure| {
                    Departure::new(&departure.event, departure.direction.as_deref(), None)
                })
                .collect();
            (departures, list.info)
        };
        Ok(DeparturesResult {
            stop: board_stop(&departures, stop_id, stop_name),
            arrivals: query.arrivals,
            page_cursor: PageCursor {
                earlier: None,
                later: later(&departures),
            },
            departures,
            realtime_as_of: time::plan_rt(info.plan_rt_ts.as_deref()),
            attribution: Attribution::default(),
            warnings: Vec::new(),
        })
    }

    /// A trip with all its stops, by the `trip_id` of a departure or leg.
    pub async fn journey(&self, trip_id: &str) -> Result<JourneyResult, Error> {
        let journey = self.call(&JourneyDetail::new(trip_id.trim())).await?;
        Ok(JourneyResult::new(trip_id.trim(), &journey, Vec::new()))
    }
}

/// The stop of a board: as the first departure names it, else as resolved.
fn board_stop(departures: &[Departure], id: String, name: Option<String>) -> Location {
    match departures.first() {
        Some(first) => Location {
            id: first.stop.id.clone().or(Some(id)),
            name: first.stop.name.clone(),
            dhid: first.stop.dhid.clone(),
        },
        None => Location {
            name: name.unwrap_or_else(|| id.clone()),
            id: Some(id),
            dhid: None,
        },
    }
}

/// The cursor after a board: a minute after its last scheduled time. A
/// board always has every departure of its last minute, so none is lost.
fn later(departures: &[Departure]) -> Option<String> {
    let last = departures
        .iter()
        .filter_map(|departure| departure.stop.time.scheduled.parse::<Timestamp>().ok())
        .max()?;
    last.checked_add(1.minute()).ok().map(time::format)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn an_empty_board_has_no_later_page() {
        assert_eq!(later(&[]), None);
        let stop = board_stop(&[], "3000010".into(), None);
        assert_eq!(stop.name, "3000010");
        assert_eq!(stop.id.as_deref(), Some("3000010"));
    }
}