rmv-core 1.0.0

Configuration, retries, stop resolution and connection status for the RMV API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! The output: the same types for JSON, YAML and the structured content of
//! the MCP tools. Times are RFC 3339 with the offset of `Europe/Berlin`,
//! like `2026-11-28T08:44:00+01:00`. Delays are whole minutes, late
//! positive, early negative.
//!
//! Texts from the API (stop names, alert texts) are data: they may contain
//! anything.

use jiff::Timestamp;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::status::{Realtime, Reason, Status};

/// Longest alert text, in bytes. Longer texts are cut.
pub const MAX_ALERT_TEXT: usize = 2048;

/// The data source and its terms. Keep it with the data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Attribution {
    pub text: String,
    /// The open data offer of RMV.
    pub sources_url: String,
    /// The terms of use of the API.
    pub usage_rules_url: String,
}

impl Default for Attribution {
    fn default() -> Self {
        Self {
            text: "Daten: Rhein-Main-Verkehrsverbund (RMV)".to_owned(),
            sources_url: "https://www.rmv.de/s/de/rmv-open-data".to_owned(),
            usage_rules_url: "https://www.rmv.de/s/de/rmv-open-data/nutzungsbedingung".to_owned(),
        }
    }
}

/// A stop, as found by name.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct StopMatch {
    /// The ID to pass instead of the name.
    pub id: String,
    pub name: String,
    /// The town or district, to tell stops of the same name apart.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub area: Option<String>,
    /// The global ID of the stop (DHID), like `de:06412:10`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dhid: Option<String>,
    pub lat: f64,
    pub lon: f64,
    /// The modes that serve the stop, like `SUBURBAN`.
    pub modes: Vec<String>,
}

/// The answer to a stop search.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct FindStopResult {
    pub query: String,
    pub stops: Vec<StopMatch>,
    pub attribution: Attribution,
    pub warnings: Vec<String>,
}

/// A stop of a connection or departure.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Location {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dhid: Option<String>,
}

/// A time by the schedule and the expected or actual one.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Time {
    pub scheduled: String,
    /// The best known time: with realtime data the expected or actual one,
    /// else the schedule.
    pub actual: String,
    /// `actual` minus `scheduled`. Absent without realtime data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delay_minutes: Option<i64>,
}

impl Time {
    pub(crate) fn new(scheduled: Timestamp, actual: Timestamp, realtime: bool) -> Self {
        Self {
            scheduled: crate::time::format(scheduled),
            actual: crate::time::format(actual),
            delay_minutes: realtime.then(|| delay_minutes(scheduled, actual)),
        }
    }
}

/// Where a leg starts or ends.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct StopEvent {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dhid: Option<String>,
    #[serde(flatten)]
    pub time: Time,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub track: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheduled_track: Option<String>,
    /// Whether boarding or alighting here is cancelled.
    pub cancelled: bool,
}

/// One leg of a connection: a ride or a walk.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Leg {
    /// Like `SUBURBAN`, `BUS` or `WALK`.
    pub mode: String,
    /// The line, like `S2`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operator: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headsign: Option<String>,
    /// For `rmv journey`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trip_id: Option<String>,
    pub from: StopEvent,
    pub to: StopEvent,
    pub duration_minutes: i64,
    /// Whether realtime data exists for this leg.
    pub realtime: bool,
    /// Whether the trip is cancelled.
    pub cancelled: bool,
    /// Whether passengers stay in the vehicle from the previous leg. RMV
    /// does not tell, so it is always false.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub stay_seated: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub alerts: Vec<Alert>,
}

/// A connection with its status.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Connection {
    /// What the caller has to know first; see the reasons.
    pub status: Status,
    /// Why the status is not `ok`, most important first.
    pub reasons: Vec<Reason>,
    /// Whether the rides have realtime data: all, some or none.
    pub realtime: Realtime,
    pub departure: Time,
    pub arrival: Time,
    pub duration_minutes: i64,
    pub transfers: i64,
    /// The largest delay of a ride, at departure or arrival.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_delay_minutes: Option<i64>,
    pub legs: Vec<Leg>,
    /// Messages about the whole connection, not about one of its legs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub alerts: Vec<Alert>,
    /// For `rmv recheck`: the same connection with current data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recheck_token: Option<String>,
}

/// Cursors for the next page, to pass as `page_cursor`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct PageCursor {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub earlier: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub later: Option<String>,
}

/// The answer to a connection search.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct TripResult {
    pub from: Location,
    pub to: Location,
    /// Sorted by departure.
    pub connections: Vec<Connection>,
    pub page_cursor: PageCursor,
    /// When RMV last updated its realtime data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub realtime_as_of: Option<String>,
    pub attribution: Attribution,
    pub warnings: Vec<String>,
}

/// A departure or arrival at a stop.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Departure {
    pub mode: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operator: Option<String>,
    /// Where the trip goes. Absent for arrivals, which have `origin`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headsign: Option<String>,
    /// Where an arriving trip comes from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub origin: Option<String>,
    /// For `rmv journey`.
    pub trip_id: String,
    /// The stop or platform, with the time of the departure or arrival.
    pub stop: StopEvent,
    pub realtime: bool,
    /// Whether this departure or arrival is cancelled.
    pub cancelled: bool,
    /// Whether the whole trip is cancelled.
    pub trip_cancelled: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub alerts: Vec<Alert>,
}

/// The departures or arrivals at a stop.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DeparturesResult {
    pub stop: Location,
    /// Whether these are arrivals instead of departures.
    pub arrivals: bool,
    pub departures: Vec<Departure>,
    pub page_cursor: PageCursor,
    /// When RMV last updated its realtime data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub realtime_as_of: Option<String>,
    pub attribution: Attribution,
    pub warnings: Vec<String>,
}

/// A stop of a trip.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct JourneyStop {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dhid: Option<String>,
    /// Absent at the first stop.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arrival: Option<Time>,
    /// Absent at the last stop.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub departure: Option<Time>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub track: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheduled_track: Option<String>,
    /// Whether the trip skips this stop.
    pub cancelled: bool,
}

/// One trip with all its stops.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct JourneyResult {
    pub trip_id: String,
    pub mode: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub operator: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headsign: Option<String>,
    pub realtime: bool,
    /// Whether the trip is cancelled.
    pub cancelled: bool,
    pub stops: Vec<JourneyStop>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub alerts: Vec<Alert>,
    /// When RMV last updated its realtime data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub realtime_as_of: Option<String>,
    pub attribution: Attribution,
    pub warnings: Vec<String>,
}

/// A service alert of RMV (HIM message).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Alert {
    pub header: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub description: String,
    /// Not given by RMV.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effect: Option<String>,
    /// Not given by RMV.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// When the alert applies.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub periods: Vec<Period>,
}

/// A period of an alert. An absent end means until further notice.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Period {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end: Option<String>,
}

/// An error as output.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ErrorBody {
    pub error: String,
    /// Like `ambiguous_stop` or `rate_limited`.
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_after_seconds: Option<u64>,
    /// For `ambiguous_stop`: the stops to choose from.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<StopMatch>,
}

/// Seconds as whole minutes, rounded half away from zero.
pub(crate) fn minutes(seconds: i64) -> i64 {
    let sign = seconds.signum();
    sign * ((seconds.abs() + 30) / 60)
}

pub(crate) fn delay_minutes(scheduled: Timestamp, actual: Timestamp) -> i64 {
    minutes(actual.as_second() - scheduled.as_second())
}

/// The text without surrounding space, unless that leaves nothing.
pub(crate) fn non_empty(text: Option<&str>) -> Option<String> {
    text.map(str::trim)
        .filter(|text| !text.is_empty())
        .map(str::to_owned)
}

/// At most [`MAX_ALERT_TEXT`] bytes, cut at a character boundary.
pub(crate) fn truncate(text: &str) -> String {
    if text.len() <= MAX_ALERT_TEXT {
        return text.to_owned();
    }
    let mut end = MAX_ALERT_TEXT - '…'.len_utf8();
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    format!("{}…", &text[..end])
}

/// The DHID among the alternative IDs of a stop: `de:06412:10`, which 2.52
/// sends as `A×de:06412:10`.
pub(crate) fn dhid(alt_ids: &[String]) -> Option<String> {
    alt_ids
        .iter()
        .map(|id| id.trim().trim_start_matches("A×"))
        .find(|id| id.starts_with("de:"))
        .map(str::to_owned)
}

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

    #[test]
    fn rounds_to_whole_minutes() {
        assert_eq!(minutes(0), 0);
        assert_eq!(minutes(29), 0);
        assert_eq!(minutes(30), 1);
        assert_eq!(minutes(-90), -2);
        assert_eq!(minutes(-89), -1);
        assert_eq!(minutes(600), 10);
    }

    #[test]
    fn cuts_long_texts() {
        assert_eq!(truncate("short"), "short");
        let long = "ä".repeat(MAX_ALERT_TEXT);
        let cut = truncate(&long);
        assert!(cut.len() <= MAX_ALERT_TEXT, "{}", cut.len());
        assert!(cut.ends_with('…'));
    }

    #[test]
    fn finds_the_dhid() {
        let ids = |ids: &[&str]| ids.iter().map(|id| (*id).to_owned()).collect::<Vec<_>>();
        assert_eq!(
            dhid(&ids(&["3000010", "de:06412:10"])).as_deref(),
            Some("de:06412:10")
        );
        assert_eq!(
            dhid(&ids(&["A×de:06412:10"])).as_deref(),
            Some("de:06412:10")
        );
        assert_eq!(dhid(&ids(&["3000010"])), None);
        assert_eq!(dhid(&[]), None);
    }

    #[test]
    fn empty_texts_are_absent() {
        assert_eq!(non_empty(Some(" S2 ")).as_deref(), Some("S2"));
        assert_eq!(non_empty(Some("  ")), None);
        assert_eq!(non_empty(None), None);
    }

    #[test]
    fn names_rmv_as_the_source() {
        let attribution = Attribution::default();
        assert!(attribution.text.contains("RMV"), "{}", attribution.text);
        assert!(
            attribution
                .usage_rules_url
                .starts_with("https://www.rmv.de/")
        );
    }
}