use std::future::IntoFuture;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
use axum::Router;
use axum::extract::{Request, State};
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use serde_json::Value;
use tokio::task::JoinHandle;
mod modify;
pub const ACCESS_ID: &str = "sim-access-id";
pub 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#";
pub 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#";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Version {
V2_39,
V2_52,
}
impl Version {
pub fn as_str(self) -> &'static str {
match self {
Self::V2_39 => "2.39",
Self::V2_52 => "2.52",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Endpoint {
LocationName,
NearbyStops,
DepartureBoard,
ArrivalBoard,
Trip,
JourneyDetail,
Recon,
}
impl Endpoint {
const ALL: [Self; 7] = [
Self::LocationName,
Self::NearbyStops,
Self::DepartureBoard,
Self::ArrivalBoard,
Self::Trip,
Self::JourneyDetail,
Self::Recon,
];
pub fn service(self) -> &'static str {
match self {
Self::LocationName => "location.name",
Self::NearbyStops => "location.nearbystops",
Self::DepartureBoard => "departureBoard",
Self::ArrivalBoard => "arrivalBoard",
Self::Trip => "trip",
Self::JourneyDetail => "journeyDetail",
Self::Recon => "recon",
}
}
}
macro_rules! embed {
($path:literal) => {
($path, include_str!(concat!("../fixtures/", $path)))
};
}
const FIXTURES: &[(&str, &str)] = &[
embed!("2.39/arrivalBoard.json"),
embed!("2.39/departureBoard.json"),
embed!("2.39/departureBoard-cancellations.json"),
embed!("2.39/journeyDetail.json"),
embed!("2.39/journeyDetail-cancelled.json"),
embed!("2.39/location.name.json"),
embed!("2.39/location.nearbystops.json"),
embed!("2.39/recon.json"),
embed!("2.39/trip.json"),
embed!("2.39/errors/auth.json"),
embed!("2.39/errors/auth.xml"),
embed!("2.39/errors/nokey.xml"),
embed!("2.52/arrivalBoard.json"),
embed!("2.52/departureBoard.json"),
embed!("2.52/journeyDetail.json"),
embed!("2.52/location.name.json"),
embed!("2.52/location.nearbystops.json"),
embed!("2.52/recon.json"),
embed!("2.52/trip.json"),
embed!("2.52/errors/auth.json"),
embed!("2.52/errors/auth.xml"),
embed!("2.52/errors/nokey.xml"),
];
pub fn fixture(version: Version, name: &str) -> Option<&'static str> {
let path = format!("{}/{name}", version.as_str());
FIXTURES
.iter()
.find(|(known, _)| *known == path)
.map(|(_, body)| *body)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Failure {
pub status: u16,
pub code: Option<String>,
pub xml: bool,
pub retry_after_seconds: Option<u64>,
pub endpoint: Option<Endpoint>,
pub times: Option<u32>,
}
impl Failure {
pub fn status(status: u16) -> Self {
Self {
status,
code: None,
xml: false,
retry_after_seconds: None,
endpoint: None,
times: None,
}
}
pub fn api(status: u16, code: &str) -> Self {
Self {
code: Some(code.to_owned()),
..Self::status(status)
}
}
pub fn quota() -> Self {
Self::api(400, "API_QUOTA")
}
pub fn too_many_requests() -> Self {
Self::api(429, "API_TOO_MANY_REQUESTS")
}
#[must_use]
pub fn xml(mut self) -> Self {
self.xml = true;
self
}
#[must_use]
pub fn retry_after(mut self, seconds: u64) -> Self {
self.retry_after_seconds = Some(seconds);
self
}
#[must_use]
pub fn on(mut self, endpoint: Endpoint) -> Self {
self.endpoint = Some(endpoint);
self
}
#[must_use]
pub fn times(mut self, times: u32) -> Self {
self.times = Some(times);
self
}
fn applies_to(&self, endpoint: Endpoint) -> bool {
self.times != Some(0) && self.endpoint.is_none_or(|target| target == endpoint)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Injection {
Cancel { journey: String },
Delay { journey: String, minutes: i64 },
NoRealtime,
ServerVersion(String),
Fixture { endpoint: Endpoint, name: String },
Fail(Failure),
Slow(Duration),
Malformed,
}
pub const REDACTED: &str = "[redacted]";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Recorded {
pub path: String,
pub query: Vec<(String, String)>,
pub user_agent: Option<String>,
}
impl Recorded {
pub fn param(&self, name: &str) -> Option<&str> {
self.query
.iter()
.find(|(key, _)| key == name)
.map(|(_, value)| value.as_str())
}
}
#[derive(Debug, Default)]
struct Inner {
injections: Vec<Injection>,
requests: Vec<Recorded>,
}
type Shared = Arc<Mutex<Inner>>;
fn lock(shared: &Shared) -> MutexGuard<'_, Inner> {
shared
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[derive(Debug)]
pub struct Sim {
address: std::net::SocketAddr,
shared: Shared,
task: JoinHandle<std::io::Result<()>>,
}
impl Sim {
pub async fn start() -> Self {
Self::start_at(0).await
}
pub async fn start_at(port: u16) -> Self {
let shared = Shared::default();
let app = Router::new()
.fallback(handle)
.with_state(Arc::clone(&shared));
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
.await
.expect("the loopback port is free");
let address = listener.local_addr().expect("the listener has an address");
let task = tokio::spawn(axum::serve(listener, app).into_future());
Self {
address,
shared,
task,
}
}
pub fn base_url(&self) -> String {
format!("http://{}/hapi/", self.address)
}
pub fn latest_url(&self) -> String {
format!("http://{}/hapi/latest/", self.address)
}
pub fn inject(&self, injection: Injection) {
lock(&self.shared).injections.push(injection);
}
pub fn clear(&self) {
lock(&self.shared).injections.clear();
}
pub fn requests(&self) -> Vec<Recorded> {
lock(&self.shared).requests.clone()
}
}
impl Drop for Sim {
fn drop(&mut self) {
self.task.abort();
}
}
fn route(path: &str) -> Option<(Version, Endpoint)> {
let rest = path.strip_prefix("/hapi/")?;
let (version, service) = match rest.strip_prefix("latest/") {
Some(service) => (Version::V2_52, service),
None => (Version::V2_39, rest),
};
let endpoint = Endpoint::ALL
.into_iter()
.find(|endpoint| endpoint.service() == service)?;
Some((version, endpoint))
}
async fn handle(State(shared): State<Shared>, request: Request) -> Response {
let uri = request.uri();
let recorded = Recorded {
path: uri.path().to_owned(),
query: form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes())
.into_owned()
.map(|(name, value)| {
let value = if name == "accessId" && !value.is_empty() && value != ACCESS_ID {
REDACTED.to_owned()
} else {
value
};
(name, value)
})
.collect(),
user_agent: request
.headers()
.get(header::USER_AGENT)
.and_then(|value| value.to_str().ok())
.map(str::to_owned),
};
let route = route(&recorded.path);
let rejected = route.and_then(|(version, _)| check_key(version, &recorded));
let (injections, failure) = {
let mut inner = lock(&shared);
inner.requests.push(recorded.clone());
let failure = route
.filter(|_| rejected.is_none())
.and_then(|(_, endpoint)| take_failure(&mut inner, endpoint));
(inner.injections.clone(), failure)
};
for injection in &injections {
if let Injection::Slow(delay) = injection {
tokio::time::sleep(*delay).await;
}
}
let Some((version, endpoint)) = route else {
return text(StatusCode::NOT_FOUND, "Not Found");
};
if let Some(response) = rejected {
return response;
}
if let Some(failure) = failure {
return fail(version, &failure);
}
answer(version, endpoint, &recorded, &injections)
}
fn take_failure(inner: &mut Inner, endpoint: Endpoint) -> Option<Failure> {
inner
.injections
.iter_mut()
.find_map(|injection| match injection {
Injection::Fail(failure) if failure.applies_to(endpoint) => {
if let Some(times) = &mut failure.times {
*times -= 1;
}
Some(failure.clone())
}
_ => None,
})
}
fn check_key(version: Version, request: &Recorded) -> Option<Response> {
let key = request.param("accessId").unwrap_or_default();
if key.is_empty() {
let body = fixture(version, "errors/nokey.xml").expect("the fixture exists");
return Some(xml(StatusCode::BAD_REQUEST, body.to_owned()));
}
if key == ACCESS_ID {
return None;
}
Some(if request.param("format") == Some("json") {
let body = fixture(version, "errors/auth.json").expect("the fixture exists");
json(StatusCode::UNAUTHORIZED, body.to_owned())
} else {
let body = fixture(version, "errors/auth.xml").expect("the fixture exists");
xml(StatusCode::UNAUTHORIZED, body.to_owned())
})
}
fn fail(version: Version, failure: &Failure) -> Response {
let status = StatusCode::from_u16(failure.status).expect("a valid status code");
let mut response = match &failure.code {
None => text(status, status.canonical_reason().unwrap_or("error")),
Some(code) if failure.xml => xml(status, error_xml(version, code)),
Some(code) => json(status, error_json(version, code)),
};
if let Some(seconds) = failure.retry_after_seconds {
response
.headers_mut()
.insert(header::RETRY_AFTER, HeaderValue::from(seconds));
}
response
}
fn server_version(version: Version) -> &'static str {
match version {
Version::V2_39 => "2.39.1",
Version::V2_52 => "2.52.0",
}
}
fn error_json(version: Version, code: &str) -> String {
serde_json::json!({
"serverVersion": server_version(version),
"dialectVersion": version.as_str(),
"errorCode": code,
"errorText": format!("sim error {code}"),
"requestId": "sim",
})
.to_string()
}
fn error_xml(version: Version, code: &str) -> String {
format!(
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"/>"#,
server_version(version),
version.as_str(),
)
}
fn fixture_name(
version: Version,
endpoint: Endpoint,
request: &Recorded,
injections: &[Injection],
) -> String {
let injected = injections
.iter()
.rev()
.find_map(|injection| match injection {
Injection::Fixture {
endpoint: target,
name,
} if *target == endpoint => Some(name.clone()),
_ => None,
});
if let Some(name) = injected {
return name;
}
if endpoint == Endpoint::JourneyDetail
&& version == Version::V2_39
&& request.param("id") == Some(CANCELLED_JOURNEY)
{
return "journeyDetail-cancelled.json".to_owned();
}
format!("{}.json", endpoint.service())
}
fn answer(
version: Version,
endpoint: Endpoint,
request: &Recorded,
injections: &[Injection],
) -> Response {
if injections.contains(&Injection::Malformed) {
return json(StatusCode::OK, "<html>".to_owned());
}
let name = fixture_name(version, endpoint, request, injections);
let body = fixture(version, &name).unwrap_or_else(|| panic!("no fixture {name}"));
let mut body: Value = serde_json::from_str(body).expect("the fixtures are valid JSON");
for injection in injections {
modify::modify(&mut body, injection);
}
json(StatusCode::OK, body.to_string())
}
fn json(status: StatusCode, body: String) -> Response {
let kind = "application/json; charset=utf-8";
(status, [(header::CONTENT_TYPE, kind)], body).into_response()
}
fn xml(status: StatusCode, body: String) -> Response {
let kind = "application/xml; charset=utf-8";
(status, [(header::CONTENT_TYPE, kind)], body).into_response()
}
fn text(status: StatusCode, body: &'static str) -> Response {
let kind = "text/plain; charset=utf-8";
(status, [(header::CONTENT_TYPE, kind)], body).into_response()
}