Skip to main content

hafas_sim/
lib.rs

1//! Fake HAFAS ReST server on loopback that serves trimmed RMV responses,
2//! for tests.
3//!
4//! The answers come from `fixtures/`, one set per dialect version: 2.39
5//! below `/hapi/` and 2.52 below `/hapi/latest/`, as on the RMV server.
6//! [`Injection`]s change them, to produce cancellations, delays and errors on
7//! demand. Every request is recorded, so tests can check what was sent, and
8//! that nothing was sent.
9//!
10//! The sim accepts only [`ACCESS_ID`]. It answers a request without a key
11//! and one with another key with the errors of the RMV server, but it never
12//! repeats the key it was sent.
13//!
14//! ```no_run
15//! # async fn run() {
16//! use hafas_sim::{Failure, Injection, Sim};
17//!
18//! let sim = Sim::start().await;
19//! sim.inject(Injection::Fail(Failure::status(503).times(1)));
20//! // point the client under test at sim.base_url() or sim.latest_url()
21//! assert_eq!(sim.requests().len(), 0);
22//! # }
23//! ```
24
25use std::future::IntoFuture;
26use std::sync::{Arc, Mutex, MutexGuard};
27use std::time::Duration;
28
29use axum::Router;
30use axum::extract::{Request, State};
31use axum::http::{HeaderValue, StatusCode, header};
32use axum::response::{IntoResponse, Response};
33use serde_json::Value;
34use tokio::task::JoinHandle;
35
36mod modify;
37
38/// The access key the sim accepts.
39pub const ACCESS_ID: &str = "sim-access-id";
40
41/// The journey of `journeyDetail-cancelled.json` (2.39): the tram 17 at
42/// 09:10, cancelled. `journeyDetail` answers with that fixture for it.
43pub const CANCELLED_JOURNEY: &str = "2|#VN#1#ST#1795783910#PI#0#ZI#36464#TA#0#DA#281126#1S#3001937#1T#910#LS#3001979#LT#939#PU#80#RT#1#CA#BTH#ZE#17#ZB#Tram 17 #PC#5#FR#3001937#FT#910#TO#3001979#TT#939#";
44
45/// The first departure of `departureBoard.json` (2.39): the S2 at 08:40.
46pub const DEPARTURE_JOURNEY: &str = "2|#VN#1#ST#1795783910#PI#0#ZI#179619#TA#3#DA#281126#1S#3006101#1T#803#LS#3004647#LT#912#PU#80#RT#1#CA#S42#ZE#S2#ZB#      S2#PC#3#FR#3006101#FT#803#TO#3004647#TT#912#";
47
48/// A dialect version of the API, with its own fixtures.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum Version {
51    /// The production version, below `/hapi/`.
52    V2_39,
53    /// The version below `/hapi/latest/`.
54    V2_52,
55}
56
57impl Version {
58    /// The dialect version, as the server names it.
59    pub fn as_str(self) -> &'static str {
60        match self {
61            Self::V2_39 => "2.39",
62            Self::V2_52 => "2.52",
63        }
64    }
65}
66
67/// The services the sim serves.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum Endpoint {
70    LocationName,
71    NearbyStops,
72    DepartureBoard,
73    ArrivalBoard,
74    Trip,
75    JourneyDetail,
76    Recon,
77}
78
79impl Endpoint {
80    const ALL: [Self; 7] = [
81        Self::LocationName,
82        Self::NearbyStops,
83        Self::DepartureBoard,
84        Self::ArrivalBoard,
85        Self::Trip,
86        Self::JourneyDetail,
87        Self::Recon,
88    ];
89
90    /// The name of the service, the last segment of its path.
91    pub fn service(self) -> &'static str {
92        match self {
93            Self::LocationName => "location.name",
94            Self::NearbyStops => "location.nearbystops",
95            Self::DepartureBoard => "departureBoard",
96            Self::ArrivalBoard => "arrivalBoard",
97            Self::Trip => "trip",
98            Self::JourneyDetail => "journeyDetail",
99            Self::Recon => "recon",
100        }
101    }
102}
103
104/// A fixture as its path and its text, compiled into the binary.
105macro_rules! embed {
106    ($path:literal) => {
107        ($path, include_str!(concat!("../fixtures/", $path)))
108    };
109}
110
111/// The fixtures, by path below `fixtures/`.
112const FIXTURES: &[(&str, &str)] = &[
113    embed!("2.39/arrivalBoard.json"),
114    embed!("2.39/departureBoard.json"),
115    embed!("2.39/departureBoard-cancellations.json"),
116    embed!("2.39/journeyDetail.json"),
117    embed!("2.39/journeyDetail-cancelled.json"),
118    embed!("2.39/location.name.json"),
119    embed!("2.39/location.nearbystops.json"),
120    embed!("2.39/recon.json"),
121    embed!("2.39/trip.json"),
122    embed!("2.39/errors/auth.json"),
123    embed!("2.39/errors/auth.xml"),
124    embed!("2.39/errors/nokey.xml"),
125    embed!("2.52/arrivalBoard.json"),
126    embed!("2.52/departureBoard.json"),
127    embed!("2.52/journeyDetail.json"),
128    embed!("2.52/location.name.json"),
129    embed!("2.52/location.nearbystops.json"),
130    embed!("2.52/recon.json"),
131    embed!("2.52/trip.json"),
132    embed!("2.52/errors/auth.json"),
133    embed!("2.52/errors/auth.xml"),
134    embed!("2.52/errors/nokey.xml"),
135];
136
137/// The fixture `name` of `version`, like `trip.json` or `errors/auth.xml`.
138pub fn fixture(version: Version, name: &str) -> Option<&'static str> {
139    let path = format!("{}/{name}", version.as_str());
140    FIXTURES
141        .iter()
142        .find(|(known, _)| *known == path)
143        .map(|(_, body)| *body)
144}
145
146/// An error answer, for [`Injection::Fail`].
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct Failure {
149    pub status: u16,
150    /// The HAFAS error code of the body. Without one, the body is the
151    /// reason of the status as text.
152    pub code: Option<String>,
153    /// Whether the HAFAS error is XML instead of JSON.
154    pub xml: bool,
155    pub retry_after_seconds: Option<u64>,
156    /// The service it applies to, or all.
157    pub endpoint: Option<Endpoint>,
158    /// How many requests it answers, or all.
159    pub times: Option<u32>,
160}
161
162impl Failure {
163    /// An answer with `status` and a body of text.
164    pub fn status(status: u16) -> Self {
165        Self {
166            status,
167            code: None,
168            xml: false,
169            retry_after_seconds: None,
170            endpoint: None,
171            times: None,
172        }
173    }
174
175    /// An answer with `status` and a HAFAS error with `code`.
176    pub fn api(status: u16, code: &str) -> Self {
177        Self {
178            code: Some(code.to_owned()),
179            ..Self::status(status)
180        }
181    }
182
183    /// The quota is used up: `API_QUOTA` with 400, as the documentation
184    /// says.
185    pub fn quota() -> Self {
186        Self::api(400, "API_QUOTA")
187    }
188
189    /// Too many requests at once: `API_TOO_MANY_REQUESTS` with 429.
190    pub fn too_many_requests() -> Self {
191        Self::api(429, "API_TOO_MANY_REQUESTS")
192    }
193
194    #[must_use]
195    pub fn xml(mut self) -> Self {
196        self.xml = true;
197        self
198    }
199
200    #[must_use]
201    pub fn retry_after(mut self, seconds: u64) -> Self {
202        self.retry_after_seconds = Some(seconds);
203        self
204    }
205
206    #[must_use]
207    pub fn on(mut self, endpoint: Endpoint) -> Self {
208        self.endpoint = Some(endpoint);
209        self
210    }
211
212    #[must_use]
213    pub fn times(mut self, times: u32) -> Self {
214        self.times = Some(times);
215        self
216    }
217
218    fn applies_to(&self, endpoint: Endpoint) -> bool {
219        self.times != Some(0) && self.endpoint.is_none_or(|target| target == endpoint)
220    }
221}
222
223/// A change to the answers of the sim. Injections stay until
224/// [`Sim::clear`].
225#[derive(Debug, Clone, PartialEq)]
226pub enum Injection {
227    /// Cancels a journey, by the `ref` of its `JourneyDetailRef`: its
228    /// departures, arrivals and legs, and its stops. Realtime times go.
229    Cancel { journey: String },
230    /// Delays a journey: its realtime times become the scheduled ones plus
231    /// `minutes`.
232    Delay { journey: String, minutes: i64 },
233    /// Removes the realtime data: times, tracks and prognoses.
234    NoRealtime,
235    /// Answers with another `serverVersion`.
236    ServerVersion(String),
237    /// Answers a service with another fixture of the version, like
238    /// `departureBoard-cancellations.json`.
239    Fixture { endpoint: Endpoint, name: String },
240    /// Answers with an error.
241    Fail(Failure),
242    /// Waits this long before answering.
243    Slow(Duration),
244    /// Answers every request with a body that is not JSON.
245    Malformed,
246}
247
248/// What a recorded request holds instead of a key that is not
249/// [`ACCESS_ID`].
250pub const REDACTED: &str = "[redacted]";
251
252/// A request the sim received. A key other than [`ACCESS_ID`] is recorded
253/// as [`REDACTED`].
254#[derive(Debug, Clone, PartialEq, Eq)]
255pub struct Recorded {
256    pub path: String,
257    /// The query parameters, decoded, in the order sent.
258    pub query: Vec<(String, String)>,
259    pub user_agent: Option<String>,
260}
261
262impl Recorded {
263    /// The value of a query parameter.
264    pub fn param(&self, name: &str) -> Option<&str> {
265        self.query
266            .iter()
267            .find(|(key, _)| key == name)
268            .map(|(_, value)| value.as_str())
269    }
270}
271
272#[derive(Debug, Default)]
273struct Inner {
274    injections: Vec<Injection>,
275    requests: Vec<Recorded>,
276}
277
278type Shared = Arc<Mutex<Inner>>;
279
280fn lock(shared: &Shared) -> MutexGuard<'_, Inner> {
281    shared
282        .lock()
283        .unwrap_or_else(std::sync::PoisonError::into_inner)
284}
285
286/// A running sim. It stops when dropped.
287#[derive(Debug)]
288pub struct Sim {
289    address: std::net::SocketAddr,
290    shared: Shared,
291    task: JoinHandle<std::io::Result<()>>,
292}
293
294impl Sim {
295    /// Starts a sim on a free port of 127.0.0.1, on the current Tokio runtime.
296    ///
297    /// # Panics
298    ///
299    /// If no loopback port can be bound.
300    pub async fn start() -> Self {
301        Self::start_at(0).await
302    }
303
304    /// Starts a sim on `port` of 127.0.0.1, a free one for 0.
305    ///
306    /// # Panics
307    ///
308    /// If the port cannot be bound.
309    pub async fn start_at(port: u16) -> Self {
310        let shared = Shared::default();
311        let app = Router::new()
312            .fallback(handle)
313            .with_state(Arc::clone(&shared));
314        let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
315            .await
316            .expect("the loopback port is free");
317        let address = listener.local_addr().expect("the listener has an address");
318        let task = tokio::spawn(axum::serve(listener, app).into_future());
319        Self {
320            address,
321            shared,
322            task,
323        }
324    }
325
326    /// The base URL of version 2.39.
327    pub fn base_url(&self) -> String {
328        format!("http://{}/hapi/", self.address)
329    }
330
331    /// The base URL of version 2.52.
332    pub fn latest_url(&self) -> String {
333        format!("http://{}/hapi/latest/", self.address)
334    }
335
336    pub fn inject(&self, injection: Injection) {
337        lock(&self.shared).injections.push(injection);
338    }
339
340    /// Removes all injections.
341    pub fn clear(&self) {
342        lock(&self.shared).injections.clear();
343    }
344
345    /// The requests received so far.
346    pub fn requests(&self) -> Vec<Recorded> {
347        lock(&self.shared).requests.clone()
348    }
349}
350
351impl Drop for Sim {
352    fn drop(&mut self) {
353        self.task.abort();
354    }
355}
356
357/// The version and the service of a path.
358fn route(path: &str) -> Option<(Version, Endpoint)> {
359    let rest = path.strip_prefix("/hapi/")?;
360    let (version, service) = match rest.strip_prefix("latest/") {
361        Some(service) => (Version::V2_52, service),
362        None => (Version::V2_39, rest),
363    };
364    let endpoint = Endpoint::ALL
365        .into_iter()
366        .find(|endpoint| endpoint.service() == service)?;
367    Some((version, endpoint))
368}
369
370async fn handle(State(shared): State<Shared>, request: Request) -> Response {
371    let uri = request.uri();
372    let recorded = Recorded {
373        path: uri.path().to_owned(),
374        query: form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes())
375            .into_owned()
376            .map(|(name, value)| {
377                // Any key but the one of the sim may be a real one: it must
378                // not end up in a recording, which tests print.
379                let value = if name == "accessId" && !value.is_empty() && value != ACCESS_ID {
380                    REDACTED.to_owned()
381                } else {
382                    value
383                };
384                (name, value)
385            })
386            .collect(),
387        user_agent: request
388            .headers()
389            .get(header::USER_AGENT)
390            .and_then(|value| value.to_str().ok())
391            .map(str::to_owned),
392    };
393    let route = route(&recorded.path);
394    // A request the key check rejects does not use up a failure.
395    let rejected = route.and_then(|(version, _)| check_key(version, &recorded));
396    let (injections, failure) = {
397        let mut inner = lock(&shared);
398        inner.requests.push(recorded.clone());
399        let failure = route
400            .filter(|_| rejected.is_none())
401            .and_then(|(_, endpoint)| take_failure(&mut inner, endpoint));
402        (inner.injections.clone(), failure)
403    };
404    for injection in &injections {
405        if let Injection::Slow(delay) = injection {
406            tokio::time::sleep(*delay).await;
407        }
408    }
409    let Some((version, endpoint)) = route else {
410        return text(StatusCode::NOT_FOUND, "Not Found");
411    };
412    if let Some(response) = rejected {
413        return response;
414    }
415    if let Some(failure) = failure {
416        return fail(version, &failure);
417    }
418    answer(version, endpoint, &recorded, &injections)
419}
420
421/// The first failure for `endpoint`, counted down.
422fn take_failure(inner: &mut Inner, endpoint: Endpoint) -> Option<Failure> {
423    inner
424        .injections
425        .iter_mut()
426        .find_map(|injection| match injection {
427            Injection::Fail(failure) if failure.applies_to(endpoint) => {
428                if let Some(times) = &mut failure.times {
429                    *times -= 1;
430                }
431                Some(failure.clone())
432            }
433            _ => None,
434        })
435}
436
437/// The answer of the RMV server to a missing or a wrong key.
438fn check_key(version: Version, request: &Recorded) -> Option<Response> {
439    let key = request.param("accessId").unwrap_or_default();
440    if key.is_empty() {
441        let body = fixture(version, "errors/nokey.xml").expect("the fixture exists");
442        return Some(xml(StatusCode::BAD_REQUEST, body.to_owned()));
443    }
444    if key == ACCESS_ID {
445        return None;
446    }
447    Some(if request.param("format") == Some("json") {
448        let body = fixture(version, "errors/auth.json").expect("the fixture exists");
449        json(StatusCode::UNAUTHORIZED, body.to_owned())
450    } else {
451        let body = fixture(version, "errors/auth.xml").expect("the fixture exists");
452        xml(StatusCode::UNAUTHORIZED, body.to_owned())
453    })
454}
455
456fn fail(version: Version, failure: &Failure) -> Response {
457    let status = StatusCode::from_u16(failure.status).expect("a valid status code");
458    let mut response = match &failure.code {
459        None => text(status, status.canonical_reason().unwrap_or("error")),
460        Some(code) if failure.xml => xml(status, error_xml(version, code)),
461        Some(code) => json(status, error_json(version, code)),
462    };
463    if let Some(seconds) = failure.retry_after_seconds {
464        response
465            .headers_mut()
466            .insert(header::RETRY_AFTER, HeaderValue::from(seconds));
467    }
468    response
469}
470
471fn server_version(version: Version) -> &'static str {
472    match version {
473        Version::V2_39 => "2.39.1",
474        Version::V2_52 => "2.52.0",
475    }
476}
477
478fn error_json(version: Version, code: &str) -> String {
479    serde_json::json!({
480        "serverVersion": server_version(version),
481        "dialectVersion": version.as_str(),
482        "errorCode": code,
483        "errorText": format!("sim error {code}"),
484        "requestId": "sim",
485    })
486    .to_string()
487}
488
489fn error_xml(version: Version, code: &str) -> String {
490    format!(
491        r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Error serverVersion="{}" dialectVersion="{}" errorCode="{code}" errorText="sim error {code}" requestId="sim" xmlns="http://hacon.de/hafas/proxy/hafas-proxy"/>"#,
492        server_version(version),
493        version.as_str(),
494    )
495}
496
497/// The fixture of a service: an injected one, the one of the journey for
498/// `journeyDetail`, or the default one.
499fn fixture_name(
500    version: Version,
501    endpoint: Endpoint,
502    request: &Recorded,
503    injections: &[Injection],
504) -> String {
505    let injected = injections
506        .iter()
507        .rev()
508        .find_map(|injection| match injection {
509            Injection::Fixture {
510                endpoint: target,
511                name,
512            } if *target == endpoint => Some(name.clone()),
513            _ => None,
514        });
515    if let Some(name) = injected {
516        return name;
517    }
518    if endpoint == Endpoint::JourneyDetail
519        && version == Version::V2_39
520        && request.param("id") == Some(CANCELLED_JOURNEY)
521    {
522        return "journeyDetail-cancelled.json".to_owned();
523    }
524    format!("{}.json", endpoint.service())
525}
526
527fn answer(
528    version: Version,
529    endpoint: Endpoint,
530    request: &Recorded,
531    injections: &[Injection],
532) -> Response {
533    if injections.contains(&Injection::Malformed) {
534        return json(StatusCode::OK, "<html>".to_owned());
535    }
536    let name = fixture_name(version, endpoint, request, injections);
537    let body = fixture(version, &name).unwrap_or_else(|| panic!("no fixture {name}"));
538    let mut body: Value = serde_json::from_str(body).expect("the fixtures are valid JSON");
539    for injection in injections {
540        modify::modify(&mut body, injection);
541    }
542    json(StatusCode::OK, body.to_string())
543}
544
545fn json(status: StatusCode, body: String) -> Response {
546    let kind = "application/json; charset=utf-8";
547    (status, [(header::CONTENT_TYPE, kind)], body).into_response()
548}
549
550fn xml(status: StatusCode, body: String) -> Response {
551    let kind = "application/xml; charset=utf-8";
552    (status, [(header::CONTENT_TYPE, kind)], body).into_response()
553}
554
555fn text(status: StatusCode, body: &'static str) -> Response {
556    let kind = "text/plain; charset=utf-8";
557    (status, [(header::CONTENT_TYPE, kind)], body).into_response()
558}