hafas 1.0.0

Client for the HAFAS ReST public transport 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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Checks the types against the extract of the XSD and the WADLs in
//! `schema/`, so a typo or a renamed field shows up here and not as a
//! silently missing value. Production and `latest/` are read together: a
//! field may be in either.
//!
//! The extract is updated by `scripts/schema-update.sh`, weekly in CI.

use std::collections::BTreeSet;

use hafas::{
    Arrival, ArrivalBoard, ArrivalList, BoardEvent, CoordLocation, Departure, DepartureBoard,
    DepartureList, Direction, Journey, JourneyDetail, JourneyDetailRef, JourneyStatus, Leg,
    LocationKind, LocationList, LocationName, LocationNote, Message, Name, NearbyStops, Note,
    Occupancy, OriginDest, Place, Platform, PlatformKind, Product, PrognosisType, Recon, Request,
    RtMode, ServiceDays, Stop, StopLocation, Trip, TripList, TripSearch, TripStatus,
};
use serde::Serialize;
use serde_json::Value;

const PRODUCTION: &str = include_str!("../schema/production.json");
const LATEST: &str = include_str!("../schema/latest.json");

/// The kind of a field: simple values end the walk, complex ones continue it.
enum Field {
    Simple,
    Complex(String),
}

struct Schemas(Vec<Value>);

impl Schemas {
    fn load() -> Self {
        Self(
            [PRODUCTION, LATEST]
                .iter()
                .map(|text| serde_json::from_str(text).expect("the extract is JSON"))
                .collect(),
        )
    }

    /// The definitions of a type in every version that has it.
    fn types<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Value> + 'a {
        self.0
            .iter()
            .map(move |schema| &schema["types"][name])
            .filter(|ty| ty.is_object())
    }

    /// Whether `name` is a complex type, not a simple one or an enum.
    fn is_complex(&self, name: &str) -> bool {
        self.types(name).next().is_some()
    }

    /// The type of a field of `ty`, an element or an attribute of it or of
    /// one of its bases: `Field::Simple` for an attribute, the simple content
    /// `value` or an element of a simple type.
    fn field(&self, ty: &str, name: &str) -> Option<Field> {
        for schema in &self.0 {
            let mut current = Some(ty.to_owned());
            while let Some(ty) = current {
                let definition = &schema["types"][&ty];
                if !definition.is_object() {
                    break;
                }
                if let Some(element) = definition["elements"].get(name) {
                    let element = element["type"].as_str().unwrap().to_owned();
                    return Some(if self.is_complex(&element) {
                        Field::Complex(element)
                    } else {
                        Field::Simple
                    });
                }
                if definition["attributes"].get(name).is_some()
                    || (name == "value" && definition["text"] == true)
                {
                    return Some(Field::Simple);
                }
                current = definition["base"].as_str().map(str::to_owned);
            }
        }
        None
    }

    /// Walks a serialized value and collects the paths of the fields that the
    /// schema lacks.
    fn walk(&self, value: &Value, ty: &str, path: &str, unknown: &mut BTreeSet<String>) {
        match value {
            Value::Array(items) => {
                for item in items {
                    self.walk(item, ty, &format!("{path}[]"), unknown);
                }
            }
            Value::Object(fields) => {
                for (key, child) in fields {
                    let path = format!("{path}.{key}");
                    // The JSON mapping puts the choice of the XSD between
                    // `StopLocation` and `CoordLocation` in one list of
                    // objects with one of these keys each.
                    if ty == "LocationList" && key == "stopLocationOrCoordLocation" {
                        self.walk(child, ty, &path, unknown);
                        continue;
                    }
                    match self.field(ty, key) {
                        None => {
                            unknown.insert(format!("{ty}: {path}"));
                        }
                        Some(Field::Complex(element)) => {
                            self.walk(child, &element, &path, unknown);
                        }
                        Some(Field::Simple) => {}
                    }
                }
            }
            _ => {}
        }
    }

    /// The type of the element `name` of `ty`.
    fn element(&self, ty: &str, name: &str) -> String {
        match self.field(ty, name) {
            Some(Field::Complex(element)) => element,
            _ => panic!("{ty} has no complex element {name}"),
        }
    }

    fn enum_values(&self, name: &str) -> BTreeSet<String> {
        let mut values = BTreeSet::new();
        for schema in &self.0 {
            if let Some(list) = schema["enums"][name].as_array() {
                values.extend(list.iter().map(|v| v.as_str().unwrap().to_owned()));
            }
        }
        assert!(!values.is_empty(), "no enum {name}");
        values
    }
}

fn unknown_fields<T: Serialize>(schemas: &Schemas, value: &T, ty: &str) -> BTreeSet<String> {
    let mut unknown = BTreeSet::new();
    let value = serde_json::to_value(value).unwrap();
    schemas.walk(&value, ty, "", &mut unknown);
    unknown
}

#[test]
fn the_walk_finds_unknown_fields_at_any_depth() {
    let schemas = Schemas::load();
    let value = serde_json::json!({
        "serverVersion": "2.39.1",
        "bogus": 1,
        "Trip": [{
            "ctxRecon": "x",
            "LegList": {"Leg": [{"Notes": {"Note": [{"value": "x", "nope": 1}]}}]},
        }],
    });
    let mut unknown = BTreeSet::new();
    schemas.walk(&value, "TripList", "", &mut unknown);
    assert_eq!(
        unknown,
        BTreeSet::from([
            "TripList: .bogus".to_owned(),
            "Note: .Trip[].LegList.Leg[].Notes.Note[].nope".to_owned(),
        ])
    );
    let value = serde_json::json!({
        "stopLocationOrCoordLocation": [
            {"StopLocation": {"extId": "1", "nope": 1}},
            {"Nowhere": {}},
        ],
    });
    let mut unknown = BTreeSet::new();
    schemas.walk(&value, "LocationList", "", &mut unknown);
    assert_eq!(
        unknown,
        BTreeSet::from([
            "StopLocation: .stopLocationOrCoordLocation[].StopLocation.nope".to_owned(),
            "LocationList: .stopLocationOrCoordLocation[].Nowhere".to_owned(),
        ])
    );
}

fn check<T: Default + Serialize>(schemas: &Schemas, ty: &str) {
    let unknown = unknown_fields(schemas, &T::default(), ty);
    assert!(unknown.is_empty(), "fields the API lacks: {unknown:?}");
}

#[test]
fn every_field_of_the_responses_exists_in_the_schema() {
    let schemas = Schemas::load();
    check::<LocationList>(&schemas, "LocationList");
    check::<DepartureList>(&schemas, "DepartureBoard");
    check::<ArrivalList>(&schemas, "ArrivalBoard");
    check::<Journey>(&schemas, "JourneyDetail");
    check::<TripList>(&schemas, "TripList");
}

#[test]
fn every_field_of_the_parts_exists_in_the_schema() {
    let schemas = Schemas::load();
    let s = &schemas;
    let stop_location = s.element("LocationList", "StopLocation");
    check::<StopLocation>(s, &stop_location);
    check::<CoordLocation>(s, &s.element("LocationList", "CoordLocation"));
    let notes = s.element(&stop_location, "LocationNotes");
    check::<LocationNote>(s, &s.element(&notes, "LocationNote"));
    let departure = s.element("DepartureBoard", "Departure");
    check::<Departure>(s, &departure);
    check::<BoardEvent>(s, &departure);
    let arrival = s.element("ArrivalBoard", "Arrival");
    check::<Arrival>(s, &arrival);
    check::<BoardEvent>(s, &arrival);
    check::<JourneyDetailRef>(s, &s.element(&departure, "JourneyDetailRef"));
    check::<Product>(s, &s.element(&departure, "Product"));
    check::<Platform>(s, &s.element(&departure, "platform"));
    check::<Occupancy>(s, &s.element(&departure, "Occupancy"));
    let notes = s.element(&departure, "Notes");
    check::<Note>(s, &s.element(&notes, "Note"));
    let messages = s.element(&departure, "Messages");
    check::<Message>(s, &s.element(&messages, "Message"));
    let stops = s.element("JourneyDetail", "Stops");
    check::<Stop>(s, &s.element(&stops, "Stop"));
    let names = s.element("JourneyDetail", "Names");
    check::<Name>(s, &s.element(&names, "Name"));
    let directions = s.element("JourneyDetail", "Directions");
    check::<Direction>(s, &s.element(&directions, "Direction"));
    check::<ServiceDays>(s, &s.element("JourneyDetail", "ServiceDays"));
    let trip = s.element("TripList", "Trip");
    check::<Trip>(s, &trip);
    check::<TripStatus>(s, &s.element(&trip, "TripStatus"));
    let legs = s.element(&trip, "LegList");
    let leg = s.element(&legs, "Leg");
    check::<Leg>(s, &leg);
    check::<OriginDest>(s, &s.element(&leg, "Origin"));
}

/// The decoded fixtures, written back: unlike the defaults, they have items
/// in their lists, so the walk reaches every nested type.
#[test]
fn every_field_of_the_decoded_fixtures_exists_in_the_schema() {
    let schemas = Schemas::load();
    let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../hafas-sim/fixtures");
    let mut unknown = BTreeSet::new();
    let mut count = 0;
    for version in hafas::DIALECT_VERSIONS {
        let dir = std::path::Path::new(fixtures).join(version);
        for entry in std::fs::read_dir(&dir).unwrap() {
            let path = entry.unwrap().path();
            if path.extension().is_none_or(|extension| extension != "json") {
                continue;
            }
            let name = path.file_name().unwrap().to_str().unwrap().to_owned();
            let body = std::fs::read(&path).unwrap();
            let decoded = |ty: &str| -> Value {
                let value = match ty {
                    "LocationList" => {
                        serde_json::to_value(serde_json::from_slice::<LocationList>(&body).unwrap())
                    }
                    "DepartureBoard" => serde_json::to_value(
                        serde_json::from_slice::<DepartureList>(&body).unwrap(),
                    ),
                    "ArrivalBoard" => {
                        serde_json::to_value(serde_json::from_slice::<ArrivalList>(&body).unwrap())
                    }
                    "JourneyDetail" => {
                        serde_json::to_value(serde_json::from_slice::<Journey>(&body).unwrap())
                    }
                    _ => serde_json::to_value(serde_json::from_slice::<TripList>(&body).unwrap()),
                };
                value.unwrap()
            };
            let ty = match name.split(['-', '.']).next().unwrap() {
                "location" => "LocationList",
                "departureBoard" => "DepartureBoard",
                "arrivalBoard" => "ArrivalBoard",
                "journeyDetail" => "JourneyDetail",
                "trip" | "recon" => "TripList",
                other => panic!("no type for the fixture {other}"),
            };
            schemas.walk(&decoded(ty), ty, &format!("{version}/{name}"), &mut unknown);
            count += 1;
        }
    }
    assert!(count >= 14, "only {count} fixtures");
    assert!(unknown.is_empty(), "fields the API lacks: {unknown:#?}");
}

#[test]
fn every_response_type_matches_its_service() {
    let schemas = Schemas::load();
    let services = [
        (LocationName::PATH, "LocationList"),
        (NearbyStops::PATH, "LocationList"),
        (DepartureBoard::PATH, "DepartureBoard"),
        (ArrivalBoard::PATH, "ArrivalBoard"),
        (JourneyDetail::PATH, "JourneyDetail"),
        (TripSearch::PATH, "TripList"),
        (Recon::PATH, "TripList"),
    ];
    for schema in &schemas.0 {
        for (path, response) in services {
            assert_eq!(
                schema["services"][path]["responses"],
                serde_json::json!([response]),
                "{path}"
            );
        }
    }
}

fn known(values: &[&str]) -> BTreeSet<String> {
    values.iter().map(|&value| value.to_owned()).collect()
}

#[test]
fn every_enum_value_exists_in_the_schema() {
    let schemas = Schemas::load();
    let checks: [(&str, &[&str]); 5] = [
        ("JourneyStatusType", JourneyStatus::KNOWN),
        ("PrognosisType", PrognosisType::KNOWN),
        ("PlatformTypeType", PlatformKind::KNOWN),
        ("Departure@type", LocationKind::KNOWN),
        ("RtModeType", RtMode::KNOWN),
    ];
    for (name, values) in checks {
        let missing: BTreeSet<_> = known(values)
            .difference(&schemas.enum_values(name))
            .cloned()
            .collect();
        assert!(missing.is_empty(), "{name} lacks {missing:?}");
    }
}

/// Checks that the service knows every parameter the request sends, and
/// that the request sends every required parameter without a default.
fn check_request<R: Request>(schemas: &Schemas, request: &R) {
    let sent: BTreeSet<&str> = request.query().iter().map(|(name, _)| *name).collect();
    let mut known = BTreeSet::new();
    for schema in &schemas.0 {
        let params = schema["services"][R::PATH]["params"]
            .as_object()
            .unwrap_or_else(|| panic!("{} is not in the schema", R::PATH));
        known.extend(params.keys().map(String::as_str));
        for (name, param) in params {
            let added_by_client = ["accessId", "format", "lang"].contains(&name.as_str());
            if param["required"] == true && param.get("default").is_none() && !added_by_client {
                assert!(sent.contains(name.as_str()), "{} needs {name}", R::PATH);
            }
        }
    }
    let unknown: BTreeSet<_> = sent.difference(&known).collect();
    assert!(unknown.is_empty(), "{} lacks {unknown:?}", R::PATH);
}

#[test]
fn every_parameter_exists_in_the_schema() {
    let schemas = Schemas::load();
    let s = &schemas;
    check_request(
        s,
        &LocationName {
            max_no: Some(5),
            kind: Some("S".to_owned()),
            products: Some(8),
            near: Some((50.1, 8.6)),
            ..LocationName::new("Hauptwache")
        },
    );
    check_request(
        s,
        &NearbyStops {
            r: Some(500),
            max_no: Some(5),
            kind: Some("S".to_owned()),
            products: Some(8),
            ..NearbyStops::new(50.1, 8.6)
        },
    );
    let board = DepartureBoard {
        date: Some("2026-11-26".to_owned()),
        time: Some("07:30".to_owned()),
        duration: Some(60),
        max_journeys: Some(10),
        products: Some(8),
        direction: Some("3000010".to_owned()),
        rt_mode: Some(RtMode::ServerDefault),
        ..DepartureBoard::new("3000010")
    };
    check_request(s, &board);
    check_request(
        s,
        &ArrivalBoard {
            date: board.date.clone(),
            time: board.time.clone(),
            duration: board.duration,
            max_journeys: board.max_journeys,
            products: board.products,
            direction: board.direction.clone(),
            rt_mode: board.rt_mode.clone(),
            ..ArrivalBoard::new("3000010")
        },
    );
    let trip = TripSearch {
        date: Some("2026-11-26".to_owned()),
        time: Some("07:30".to_owned()),
        search_for_arrival: Some(true),
        num_f: Some(3),
        num_b: Some(1),
        context: Some("context".to_owned()),
        max_change: Some(2),
        products: Some(8),
        rt_mode: Some(RtMode::Realtime),
        passlist: Some(true),
        ..TripSearch::new(
            Place::Id("3000010".to_owned()),
            Place::Coord {
                lat: 50.1,
                lon: 8.6,
            },
        )
    };
    check_request(s, &trip);
    check_request(
        s,
        &TripSearch {
            origin: Place::Coord {
                lat: 50.1,
                lon: 8.6,
            },
            destination: Place::Id("3004734".to_owned()),
            ..trip
        },
    );
    check_request(
        s,
        &JourneyDetail {
            date: Some("2026-11-26".to_owned()),
            rt_mode: Some(RtMode::Full),
            ..JourneyDetail::new("1|1|1|80|26112026")
        },
    );
    check_request(
        s,
        &Recon {
            rt_mode: Some(RtMode::Full),
            passlist: Some(true),
            ..Recon::new("ctx")
        },
    );
}