rmv-core 1.0.0

Configuration, retries, stop resolution and connection status for the RMV API
Documentation
//! Connection searches and the recheck of one connection.

use hafas::{Place, Recon, RtMode, TripList, TripSearch};

use crate::model::{Attribution, Connection, Location, PageCursor, TripResult};
use crate::service::Rmv;
use crate::{Error, convert, modes, resolve, time};

/// The most connections of one search: what the API gives at once.
pub const MAX_CONNECTIONS: u32 = 6;

/// A search for connections.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TripQuery {
    /// A stop ID, a name that names one stop, or `LAT,LON`.
    pub from: String,
    pub to: String,
    /// `None`: now.
    pub time: Option<jiff::Timestamp>,
    /// Whether `time` is the latest arrival.
    pub arrive_by: bool,
    /// At most [`MAX_CONNECTIONS`].
    pub count: u32,
    /// Only these modes. Empty: all.
    pub modes: Vec<String>,
    pub max_transfers: Option<u32>,
    /// A cursor of an earlier result. It replaces `time`.
    pub page_cursor: Option<String>,
    /// Whether the search takes delays and cancellations into account, not
    /// only shows them.
    pub realtime_routing: bool,
}

/// A place of a search, with the name to show if the answer has none.
struct Endpoint {
    place: Place,
    location: Location,
}

impl Rmv {
    async fn endpoint(&self, input: &str) -> Result<Endpoint, Error> {
        if let Some((lat, lon)) = resolve::coordinates(input) {
            return Ok(Endpoint {
                place: Place::Coord { lat, lon },
                location: Location {
                    id: None,
                    name: input.trim().to_owned(),
                    dhid: None,
                },
            });
        }
        let (id, name) = self.resolve_stop(input).await?;
        Ok(Endpoint {
            location: Location {
                name: name.unwrap_or_else(|| id.clone()),
                id: Some(id.clone()),
                dhid: None,
            },
            place: Place::Id(id),
        })
    }

    /// Connections between two places.
    pub async fn trip(&self, query: &TripQuery) -> Result<TripResult, Error> {
        let products = modes::products(&query.modes)?;
        if query.max_transfers.is_some_and(|max| max > 11) {
            return Err(Error::BadRequest {
                message: "max_transfers is at most 11".to_owned(),
            });
        }
        let from = self.endpoint(&query.from).await?;
        let to = self.endpoint(&query.to).await?;
        let cursor = query
            .page_cursor
            .as_deref()
            .map(str::trim)
            .filter(|c| !c.is_empty());
        let (date, time) = match cursor {
            Some(_) => (None, None),
            None => query.time.map(time::request).unzip(),
        };
        let count = query.count.clamp(1, MAX_CONNECTIONS);
        let request = TripSearch {
            date,
            time,
            search_for_arrival: query.arrive_by.then_some(true),
            num_f: Some(count),
            context: cursor.map(str::to_owned),
            max_change: query.max_transfers,
            products,
            rt_mode: Some(if query.realtime_routing {
                RtMode::Realtime
            } else {
                RtMode::Infos
            }),
            passlist: Some(false),
            ..TripSearch::new(from.place, to.place)
        };
        let mut list = self.call_or_none(&request).await?.unwrap_or_default();
        let mut warnings = Vec::new();
        // Before an arrival, the API gives only the connections it finds in
        // its first window; one earlier page fills the result up.
        if query.arrive_by
            && cursor.is_none()
            && list.trips.len() < count as usize
            && let Some(earlier) = list.scr_b.clone()
        {
            // Only as many as are missing, so the result stays within `count`.
            let missing = count as usize - list.trips.len();
            let request = TripSearch {
                context: Some(earlier),
                num_f: u32::try_from(missing).ok(),
                ..request
            };
            let more = self.call_or_none(&request).await;
            fill_up(&mut list, more, missing, &mut warnings);
        }
        Ok(self.trip_result(list, from.location, to.location, warnings))
    }

    /// The connection of a `recheck_token`, with current data.
    pub async fn recheck(&self, token: &str) -> Result<TripResult, Error> {
        let token = token.trim();
        if token.is_empty() {
            return Err(Error::BadRequest {
                message: "the recheck token is empty".to_owned(),
            });
        }
        let request = Recon {
            rt_mode: Some(RtMode::Infos),
            passlist: Some(false),
            ..Recon::new(token)
        };
        let list = self.call(&request).await?;
        let unknown = || Location {
            id: None,
            name: String::new(),
            dhid: None,
        };
        Ok(self.trip_result(list, unknown(), unknown(), Vec::new()))
    }

    /// The result of `list`, each connection once, sorted by departure.
    fn trip_result(
        &self,
        mut list: TripList,
        from: Location,
        to: Location,
        warnings: Vec<String>,
    ) -> TripResult {
        dedupe(&mut list.trips);
        list.trips.sort_by_key(convert::departure);
        let now = (self.clock)();
        let first = list.trips.first();
        let from = first
            .and_then(|trip| {
                trip.legs
                    .first()
                    .map(|leg| &leg.origin)
                    .or(trip.origin.as_ref())
            })
            .map_or(from, Location::from);
        let to = first
            .and_then(|trip| {
                trip.legs
                    .last()
                    .map(|leg| &leg.destination)
                    .or(trip.destination.as_ref())
            })
            .map_or(to, Location::from);
        TripResult {
            from,
            to,
            connections: list
                .trips
                .iter()
                .map(|trip| Connection::new(trip, now, self.delay_threshold_minutes))
                .collect(),
            page_cursor: PageCursor {
                earlier: list.scr_b,
                later: list.scr_f,
            },
            realtime_as_of: time::plan_rt(list.info.plan_rt_ts.as_deref()),
            attribution: Attribution::default(),
            warnings,
        }
    }
}

/// Removes the trips that come again, by their `ctxRecon`: pages can
/// overlap.
fn dedupe(trips: &mut Vec<hafas::Trip>) {
    let mut seen: Vec<String> = Vec::new();
    trips.retain(|trip| {
        let Some(ctx) = trip.ctx_recon.as_deref() else {
            return true;
        };
        let new = !seen.iter().any(|known| known == ctx);
        if new {
            seen.push(ctx.to_owned());
        }
        new
    });
}

/// Adds the last `missing` connections of the earlier page to `list`: the
/// ones closest to the arrival. Without them, the result is only shorter,
/// so an error is a warning.
fn fill_up(
    list: &mut TripList,
    earlier: Result<Option<TripList>, Error>,
    missing: usize,
    warnings: &mut Vec<String>,
) {
    match earlier {
        Ok(more) => {
            let mut more = more.unwrap_or_default();
            dedupe(&mut more.trips);
            more.trips.retain(|trip| {
                trip.ctx_recon.is_none()
                    || !list
                        .trips
                        .iter()
                        .any(|known| known.ctx_recon == trip.ctx_recon)
            });
            let skip = more.trips.len().saturating_sub(missing);
            list.trips.extend(more.trips.into_iter().skip(skip));
            list.scr_b = more.scr_b;
        }
        Err(error) => warnings.push(format!("no earlier connections: {error}")),
    }
}

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

    #[test]
    fn keeps_each_trip_once() {
        let trip = |ctx: Option<&str>| hafas::Trip {
            ctx_recon: ctx.map(str::to_owned),
            ..hafas::Trip::default()
        };
        let mut trips = vec![trip(Some("a")), trip(None), trip(Some("a")), trip(None)];
        dedupe(&mut trips);
        let left: Vec<Option<&str>> = trips.iter().map(|t| t.ctx_recon.as_deref()).collect();
        assert_eq!(left, [Some("a"), None, None]);
    }

    #[test]
    fn a_failed_earlier_page_is_a_warning() {
        let mut list = TripList {
            scr_b: Some("before".to_owned()),
            ..TripList::default()
        };
        let mut warnings = Vec::new();
        fill_up(
            &mut list,
            Err(Error::Unavailable {
                message: "down".to_owned(),
            }),
            1,
            &mut warnings,
        );
        assert_eq!(list.scr_b.as_deref(), Some("before"));
        assert_eq!(warnings.len(), 1);
        assert!(
            warnings[0].starts_with("no earlier connections: "),
            "{warnings:?}"
        );
        fill_up(&mut list, Ok(None), 1, &mut warnings);
        assert_eq!(list.scr_b, None);
    }

    #[test]
    fn the_earlier_page_only_fills_up() {
        let trip = |ctx: &str| hafas::Trip {
            ctx_recon: Some(ctx.to_owned()),
            ..hafas::Trip::default()
        };
        let mut list = TripList {
            trips: vec![trip("c")],
            ..TripList::default()
        };
        let earlier = TripList {
            trips: vec![trip("x"), trip("a"), trip("b"), trip("c")],
            ..TripList::default()
        };
        let mut warnings = Vec::new();
        fill_up(&mut list, Ok(Some(earlier)), 2, &mut warnings);
        let left: Vec<Option<&str>> = list.trips.iter().map(|t| t.ctx_recon.as_deref()).collect();
        assert_eq!(left, [Some("c"), Some("a"), Some("b")]);
        assert_eq!(warnings, Vec::<String>::new());
    }
}