Skip to main content

rmv_core/
model.rs

1//! The output: the same types for JSON, YAML and the structured content of
2//! the MCP tools. Times are RFC 3339 with the offset of `Europe/Berlin`,
3//! like `2026-11-28T08:44:00+01:00`. Delays are whole minutes, late
4//! positive, early negative.
5//!
6//! Texts from the API (stop names, alert texts) are data: they may contain
7//! anything.
8
9use jiff::Timestamp;
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12
13use crate::status::{Realtime, Reason, Status};
14
15/// Longest alert text, in bytes. Longer texts are cut.
16pub const MAX_ALERT_TEXT: usize = 2048;
17
18/// The data source and its terms. Keep it with the data.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
20pub struct Attribution {
21    pub text: String,
22    /// The open data offer of RMV.
23    pub sources_url: String,
24    /// The terms of use of the API.
25    pub usage_rules_url: String,
26}
27
28impl Default for Attribution {
29    fn default() -> Self {
30        Self {
31            text: "Daten: Rhein-Main-Verkehrsverbund (RMV)".to_owned(),
32            sources_url: "https://www.rmv.de/s/de/rmv-open-data".to_owned(),
33            usage_rules_url: "https://www.rmv.de/s/de/rmv-open-data/nutzungsbedingung".to_owned(),
34        }
35    }
36}
37
38/// A stop, as found by name.
39#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
40pub struct StopMatch {
41    /// The ID to pass instead of the name.
42    pub id: String,
43    pub name: String,
44    /// The town or district, to tell stops of the same name apart.
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub area: Option<String>,
47    /// The global ID of the stop (DHID), like `de:06412:10`.
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub dhid: Option<String>,
50    pub lat: f64,
51    pub lon: f64,
52    /// The modes that serve the stop, like `SUBURBAN`.
53    pub modes: Vec<String>,
54}
55
56/// The answer to a stop search.
57#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
58pub struct FindStopResult {
59    pub query: String,
60    pub stops: Vec<StopMatch>,
61    pub attribution: Attribution,
62    pub warnings: Vec<String>,
63}
64
65/// A stop of a connection or departure.
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
67pub struct Location {
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub id: Option<String>,
70    pub name: String,
71    #[serde(skip_serializing_if = "Option::is_none")]
72    pub dhid: Option<String>,
73}
74
75/// A time by the schedule and the expected or actual one.
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
77pub struct Time {
78    pub scheduled: String,
79    /// The best known time: with realtime data the expected or actual one,
80    /// else the schedule.
81    pub actual: String,
82    /// `actual` minus `scheduled`. Absent without realtime data.
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub delay_minutes: Option<i64>,
85}
86
87impl Time {
88    pub(crate) fn new(scheduled: Timestamp, actual: Timestamp, realtime: bool) -> Self {
89        Self {
90            scheduled: crate::time::format(scheduled),
91            actual: crate::time::format(actual),
92            delay_minutes: realtime.then(|| delay_minutes(scheduled, actual)),
93        }
94    }
95}
96
97/// Where a leg starts or ends.
98#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
99pub struct StopEvent {
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub id: Option<String>,
102    pub name: String,
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub dhid: Option<String>,
105    #[serde(flatten)]
106    pub time: Time,
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub track: Option<String>,
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub scheduled_track: Option<String>,
111    /// Whether boarding or alighting here is cancelled.
112    pub cancelled: bool,
113}
114
115/// One leg of a connection: a ride or a walk.
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
117pub struct Leg {
118    /// Like `SUBURBAN`, `BUS` or `WALK`.
119    pub mode: String,
120    /// The line, like `S2`.
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub line: Option<String>,
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub operator: Option<String>,
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub headsign: Option<String>,
127    /// For `rmv journey`.
128    #[serde(skip_serializing_if = "Option::is_none")]
129    pub trip_id: Option<String>,
130    pub from: StopEvent,
131    pub to: StopEvent,
132    pub duration_minutes: i64,
133    /// Whether realtime data exists for this leg.
134    pub realtime: bool,
135    /// Whether the trip is cancelled.
136    pub cancelled: bool,
137    /// Whether passengers stay in the vehicle from the previous leg. RMV
138    /// does not tell, so it is always false.
139    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
140    pub stay_seated: bool,
141    #[serde(default, skip_serializing_if = "Vec::is_empty")]
142    pub alerts: Vec<Alert>,
143}
144
145/// A connection with its status.
146#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
147pub struct Connection {
148    /// What the caller has to know first; see the reasons.
149    pub status: Status,
150    /// Why the status is not `ok`, most important first.
151    pub reasons: Vec<Reason>,
152    /// Whether the rides have realtime data: all, some or none.
153    pub realtime: Realtime,
154    pub departure: Time,
155    pub arrival: Time,
156    pub duration_minutes: i64,
157    pub transfers: i64,
158    /// The largest delay of a ride, at departure or arrival.
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub max_delay_minutes: Option<i64>,
161    pub legs: Vec<Leg>,
162    /// Messages about the whole connection, not about one of its legs.
163    #[serde(default, skip_serializing_if = "Vec::is_empty")]
164    pub alerts: Vec<Alert>,
165    /// For `rmv recheck`: the same connection with current data.
166    #[serde(skip_serializing_if = "Option::is_none")]
167    pub recheck_token: Option<String>,
168}
169
170/// Cursors for the next page, to pass as `page_cursor`.
171#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
172pub struct PageCursor {
173    #[serde(skip_serializing_if = "Option::is_none")]
174    pub earlier: Option<String>,
175    #[serde(skip_serializing_if = "Option::is_none")]
176    pub later: Option<String>,
177}
178
179/// The answer to a connection search.
180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
181pub struct TripResult {
182    pub from: Location,
183    pub to: Location,
184    /// Sorted by departure.
185    pub connections: Vec<Connection>,
186    pub page_cursor: PageCursor,
187    /// When RMV last updated its realtime data.
188    #[serde(skip_serializing_if = "Option::is_none")]
189    pub realtime_as_of: Option<String>,
190    pub attribution: Attribution,
191    pub warnings: Vec<String>,
192}
193
194/// A departure or arrival at a stop.
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
196pub struct Departure {
197    pub mode: String,
198    #[serde(skip_serializing_if = "Option::is_none")]
199    pub line: Option<String>,
200    #[serde(skip_serializing_if = "Option::is_none")]
201    pub operator: Option<String>,
202    /// Where the trip goes. Absent for arrivals, which have `origin`.
203    #[serde(skip_serializing_if = "Option::is_none")]
204    pub headsign: Option<String>,
205    /// Where an arriving trip comes from.
206    #[serde(skip_serializing_if = "Option::is_none")]
207    pub origin: Option<String>,
208    /// For `rmv journey`.
209    pub trip_id: String,
210    /// The stop or platform, with the time of the departure or arrival.
211    pub stop: StopEvent,
212    pub realtime: bool,
213    /// Whether this departure or arrival is cancelled.
214    pub cancelled: bool,
215    /// Whether the whole trip is cancelled.
216    pub trip_cancelled: bool,
217    #[serde(default, skip_serializing_if = "Vec::is_empty")]
218    pub alerts: Vec<Alert>,
219}
220
221/// The departures or arrivals at a stop.
222#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
223pub struct DeparturesResult {
224    pub stop: Location,
225    /// Whether these are arrivals instead of departures.
226    pub arrivals: bool,
227    pub departures: Vec<Departure>,
228    pub page_cursor: PageCursor,
229    /// When RMV last updated its realtime data.
230    #[serde(skip_serializing_if = "Option::is_none")]
231    pub realtime_as_of: Option<String>,
232    pub attribution: Attribution,
233    pub warnings: Vec<String>,
234}
235
236/// A stop of a trip.
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
238pub struct JourneyStop {
239    #[serde(skip_serializing_if = "Option::is_none")]
240    pub id: Option<String>,
241    pub name: String,
242    #[serde(skip_serializing_if = "Option::is_none")]
243    pub dhid: Option<String>,
244    /// Absent at the first stop.
245    #[serde(skip_serializing_if = "Option::is_none")]
246    pub arrival: Option<Time>,
247    /// Absent at the last stop.
248    #[serde(skip_serializing_if = "Option::is_none")]
249    pub departure: Option<Time>,
250    #[serde(skip_serializing_if = "Option::is_none")]
251    pub track: Option<String>,
252    #[serde(skip_serializing_if = "Option::is_none")]
253    pub scheduled_track: Option<String>,
254    /// Whether the trip skips this stop.
255    pub cancelled: bool,
256}
257
258/// One trip with all its stops.
259#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
260pub struct JourneyResult {
261    pub trip_id: String,
262    pub mode: String,
263    #[serde(skip_serializing_if = "Option::is_none")]
264    pub line: Option<String>,
265    #[serde(skip_serializing_if = "Option::is_none")]
266    pub operator: Option<String>,
267    #[serde(skip_serializing_if = "Option::is_none")]
268    pub headsign: Option<String>,
269    pub realtime: bool,
270    /// Whether the trip is cancelled.
271    pub cancelled: bool,
272    pub stops: Vec<JourneyStop>,
273    #[serde(default, skip_serializing_if = "Vec::is_empty")]
274    pub alerts: Vec<Alert>,
275    /// When RMV last updated its realtime data.
276    #[serde(skip_serializing_if = "Option::is_none")]
277    pub realtime_as_of: Option<String>,
278    pub attribution: Attribution,
279    pub warnings: Vec<String>,
280}
281
282/// A service alert of RMV (HIM message).
283#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
284pub struct Alert {
285    pub header: String,
286    #[serde(skip_serializing_if = "String::is_empty")]
287    pub description: String,
288    /// Not given by RMV.
289    #[serde(skip_serializing_if = "Option::is_none")]
290    pub effect: Option<String>,
291    /// Not given by RMV.
292    #[serde(skip_serializing_if = "Option::is_none")]
293    pub severity: Option<String>,
294    #[serde(skip_serializing_if = "Option::is_none")]
295    pub url: Option<String>,
296    /// When the alert applies.
297    #[serde(default, skip_serializing_if = "Vec::is_empty")]
298    pub periods: Vec<Period>,
299}
300
301/// A period of an alert. An absent end means until further notice.
302#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
303pub struct Period {
304    #[serde(skip_serializing_if = "Option::is_none")]
305    pub start: Option<String>,
306    #[serde(skip_serializing_if = "Option::is_none")]
307    pub end: Option<String>,
308}
309
310/// An error as output.
311#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
312pub struct ErrorBody {
313    pub error: String,
314    /// Like `ambiguous_stop` or `rate_limited`.
315    pub status: String,
316    #[serde(skip_serializing_if = "Option::is_none")]
317    pub retry_after_seconds: Option<u64>,
318    /// For `ambiguous_stop`: the stops to choose from.
319    #[serde(default, skip_serializing_if = "Vec::is_empty")]
320    pub candidates: Vec<StopMatch>,
321}
322
323/// Seconds as whole minutes, rounded half away from zero.
324pub(crate) fn minutes(seconds: i64) -> i64 {
325    let sign = seconds.signum();
326    sign * ((seconds.abs() + 30) / 60)
327}
328
329pub(crate) fn delay_minutes(scheduled: Timestamp, actual: Timestamp) -> i64 {
330    minutes(actual.as_second() - scheduled.as_second())
331}
332
333/// The text without surrounding space, unless that leaves nothing.
334pub(crate) fn non_empty(text: Option<&str>) -> Option<String> {
335    text.map(str::trim)
336        .filter(|text| !text.is_empty())
337        .map(str::to_owned)
338}
339
340/// At most [`MAX_ALERT_TEXT`] bytes, cut at a character boundary.
341pub(crate) fn truncate(text: &str) -> String {
342    if text.len() <= MAX_ALERT_TEXT {
343        return text.to_owned();
344    }
345    let mut end = MAX_ALERT_TEXT - '…'.len_utf8();
346    while !text.is_char_boundary(end) {
347        end -= 1;
348    }
349    format!("{}…", &text[..end])
350}
351
352/// The DHID among the alternative IDs of a stop: `de:06412:10`, which 2.52
353/// sends as `A×de:06412:10`.
354pub(crate) fn dhid(alt_ids: &[String]) -> Option<String> {
355    alt_ids
356        .iter()
357        .map(|id| id.trim().trim_start_matches("A×"))
358        .find(|id| id.starts_with("de:"))
359        .map(str::to_owned)
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365
366    #[test]
367    fn rounds_to_whole_minutes() {
368        assert_eq!(minutes(0), 0);
369        assert_eq!(minutes(29), 0);
370        assert_eq!(minutes(30), 1);
371        assert_eq!(minutes(-90), -2);
372        assert_eq!(minutes(-89), -1);
373        assert_eq!(minutes(600), 10);
374    }
375
376    #[test]
377    fn cuts_long_texts() {
378        assert_eq!(truncate("short"), "short");
379        let long = "ä".repeat(MAX_ALERT_TEXT);
380        let cut = truncate(&long);
381        assert!(cut.len() <= MAX_ALERT_TEXT, "{}", cut.len());
382        assert!(cut.ends_with('…'));
383    }
384
385    #[test]
386    fn finds_the_dhid() {
387        let ids = |ids: &[&str]| ids.iter().map(|id| (*id).to_owned()).collect::<Vec<_>>();
388        assert_eq!(
389            dhid(&ids(&["3000010", "de:06412:10"])).as_deref(),
390            Some("de:06412:10")
391        );
392        assert_eq!(
393            dhid(&ids(&["A×de:06412:10"])).as_deref(),
394            Some("de:06412:10")
395        );
396        assert_eq!(dhid(&ids(&["3000010"])), None);
397        assert_eq!(dhid(&[]), None);
398    }
399
400    #[test]
401    fn empty_texts_are_absent() {
402        assert_eq!(non_empty(Some(" S2 ")).as_deref(), Some("S2"));
403        assert_eq!(non_empty(Some("  ")), None);
404        assert_eq!(non_empty(None), None);
405    }
406
407    #[test]
408    fn names_rmv_as_the_source() {
409        let attribution = Attribution::default();
410        assert!(attribution.text.contains("RMV"), "{}", attribution.text);
411        assert!(
412            attribution
413                .usage_rules_url
414                .starts_with("https://www.rmv.de/")
415        );
416    }
417}