1use 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
38pub const ACCESS_ID: &str = "sim-access-id";
40
41pub 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
45pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum Version {
51 V2_39,
53 V2_52,
55}
56
57impl Version {
58 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#[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 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
104macro_rules! embed {
106 ($path:literal) => {
107 ($path, include_str!(concat!("../fixtures/", $path)))
108 };
109}
110
111const 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
137pub 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#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct Failure {
149 pub status: u16,
150 pub code: Option<String>,
153 pub xml: bool,
155 pub retry_after_seconds: Option<u64>,
156 pub endpoint: Option<Endpoint>,
158 pub times: Option<u32>,
160}
161
162impl Failure {
163 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 pub fn api(status: u16, code: &str) -> Self {
177 Self {
178 code: Some(code.to_owned()),
179 ..Self::status(status)
180 }
181 }
182
183 pub fn quota() -> Self {
186 Self::api(400, "API_QUOTA")
187 }
188
189 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#[derive(Debug, Clone, PartialEq)]
226pub enum Injection {
227 Cancel { journey: String },
230 Delay { journey: String, minutes: i64 },
233 NoRealtime,
235 ServerVersion(String),
237 Fixture { endpoint: Endpoint, name: String },
240 Fail(Failure),
242 Slow(Duration),
244 Malformed,
246}
247
248pub const REDACTED: &str = "[redacted]";
251
252#[derive(Debug, Clone, PartialEq, Eq)]
255pub struct Recorded {
256 pub path: String,
257 pub query: Vec<(String, String)>,
259 pub user_agent: Option<String>,
260}
261
262impl Recorded {
263 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#[derive(Debug)]
288pub struct Sim {
289 address: std::net::SocketAddr,
290 shared: Shared,
291 task: JoinHandle<std::io::Result<()>>,
292}
293
294impl Sim {
295 pub async fn start() -> Self {
301 Self::start_at(0).await
302 }
303
304 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 pub fn base_url(&self) -> String {
328 format!("http://{}/hapi/", self.address)
329 }
330
331 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 pub fn clear(&self) {
342 lock(&self.shared).injections.clear();
343 }
344
345 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
357fn 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 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 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
421fn 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
437fn 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
497fn 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}