hafas-sim 1.0.0

Fake HAFAS ReST server built from trimmed RMV responses, for tests
Documentation
//! The injections that change the data of an answer: `Cancel`, `Delay`,
//! `NoRealtime` and `ServerVersion`.

use jiff::SignedDuration;
use jiff::civil::DateTime;
use serde_json::Value;

use crate::Injection;

/// Applies an injection that changes the data.
pub(crate) fn modify(body: &mut Value, injection: &Injection) {
    match injection {
        Injection::Cancel { journey } => {
            for_journey(body, journey, &mut |item| cancel(item, journey));
        }
        Injection::Delay { journey, minutes } => {
            for_journey(body, journey, &mut |item| delay(item, journey, *minutes));
        }
        Injection::NoRealtime => no_realtime(body),
        Injection::ServerVersion(server) => body["serverVersion"] = server.as_str().into(),
        _ => {}
    }
}

/// Calls `f` with every object of the journey: departures, arrivals and legs
/// with its `JourneyDetailRef`, and a journey detail with its `ref`.
fn for_journey(value: &mut Value, journey: &str, f: &mut impl FnMut(&mut Value)) {
    match value {
        Value::Object(map) => {
            let reference = map
                .get("JourneyDetailRef")
                .and_then(|reference| reference.get("ref"))
                .or_else(|| map.get("ref"));
            if reference.and_then(Value::as_str) == Some(journey) {
                f(value);
                return;
            }
            for child in map.values_mut() {
                for_journey(child, journey, f);
            }
        }
        Value::Array(items) => {
            for item in items {
                for_journey(item, journey, f);
            }
        }
        _ => {}
    }
}

/// Calls `f` with every object below `value`, `value` included. With a
/// `journey`, objects of another journey (with another `JourneyDetailRef`,
/// like the alternatives of `Freq`) are left out, with all below them.
fn for_each_object(
    value: &mut Value,
    journey: Option<&str>,
    f: &mut impl FnMut(&mut serde_json::Map<String, Value>),
) {
    match value {
        Value::Object(map) => {
            let other = map
                .get("JourneyDetailRef")
                .and_then(|reference| reference.get("ref"))
                .and_then(Value::as_str)
                .zip(journey)
                .is_some_and(|(reference, journey)| reference != journey);
            if other {
                return;
            }
            f(map);
            for child in map.values_mut() {
                for_each_object(child, journey, f);
            }
        }
        Value::Array(items) => {
            for item in items {
                for_each_object(item, journey, f);
            }
        }
        _ => {}
    }
}

/// The scheduled time fields and their realtime ones: of a board event or
/// an end of a leg, and of the departure and the arrival at a stop.
const TIMES: [(&str, &str, &str, &str); 3] = [
    ("time", "date", "rtTime", "rtDate"),
    ("depTime", "depDate", "rtDepTime", "rtDepDate"),
    ("arrTime", "arrDate", "rtArrTime", "rtArrDate"),
];

/// Whether a key holds realtime data.
fn is_realtime(key: &str) -> bool {
    let realtime = key
        .strip_prefix("rt")
        .is_some_and(|rest| rest.starts_with(char::is_uppercase));
    realtime || key.ends_with("rognosisType") || key == "planRtTs"
}

fn cancel(item: &mut Value, journey: &str) {
    item["cancelled"] = Value::Bool(true);
    for_each_object(item, Some(journey), &mut |map| {
        map.retain(|key, _| !is_realtime(key));
        // The ends of a leg and the stops of a journey are cancelled too.
        if TIMES.iter().any(|(time, ..)| map.contains_key(*time)) {
            map.insert("cancelled".to_owned(), Value::Bool(true));
        }
        if map.contains_key("depTime") {
            map.insert("cancelledDeparture".to_owned(), Value::Bool(true));
        }
        if map.contains_key("arrTime") {
            map.insert("cancelledArrival".to_owned(), Value::Bool(true));
        }
    });
}

fn delay(item: &mut Value, journey: &str, minutes: i64) {
    for_each_object(item, Some(journey), &mut |map| {
        for (time, date, rt_time, rt_date) in TIMES {
            let (Some(Value::String(t)), Some(Value::String(d))) = (map.get(time), map.get(date))
            else {
                continue;
            };
            let scheduled: DateTime = format!("{d}T{t}").parse().expect("the fixture times parse");
            let shifted = scheduled + SignedDuration::from_mins(minutes);
            let (t, d) = (shifted.time().to_string(), shifted.date().to_string());
            map.insert(rt_time.to_owned(), t.into());
            map.insert(rt_date.to_owned(), d.into());
        }
    });
}

fn no_realtime(body: &mut Value) {
    for_each_object(body, None, &mut |map| {
        map.retain(|key, _| !is_realtime(key));
    });
}