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 jiff::{SignedDuration, Timestamp};
use serde_json::Value;
use tokio::task::JoinHandle;
pub const DIRECT_TRIP: &str = "20261126_20:59_de-DELFI_3490143191";
pub const DEPARTURE_TRIP: &str = "20261126_20:33_de-DELFI_3031893234";
pub const FEEDER_TRIP: &str = "20261126_21:20_de-DELFI_3031889606";
pub const CONNECTING_TRIP: &str = "20261126_21:25_de-DELFI_3126800675";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Endpoint {
Plan,
Stoptimes,
Trip,
Geocode,
ReverseGeocode,
}
impl Endpoint {
const ALL: [Self; 5] = [
Self::Plan,
Self::Stoptimes,
Self::Trip,
Self::Geocode,
Self::ReverseGeocode,
];
pub fn path(self) -> &'static str {
match self {
Self::Plan => "/api/v6/plan",
Self::Stoptimes => "/api/v6/stoptimes",
Self::Trip => "/api/v6/trip",
Self::Geocode => "/api/v1/geocode",
Self::ReverseGeocode => "/api/v1/reverse-geocode",
}
}
fn fixture(self) -> &'static str {
match self {
Self::Plan => include_str!("../fixtures/plan.json"),
Self::Stoptimes => include_str!("../fixtures/stoptimes.json"),
Self::Trip => include_str!("../fixtures/trip.json"),
Self::Geocode => include_str!("../fixtures/geocode.json"),
Self::ReverseGeocode => include_str!("../fixtures/reverse-geocode.json"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Injection {
Cancel { trip_id: String },
CancelStop { trip_id: String, stop_id: String },
Delay { trip_id: String, minutes: i64 },
NoRealtime,
Respond {
endpoint: Endpoint,
status: u16,
body: String,
},
RateLimited { retry_after_seconds: u64 },
Slow(Duration),
Malformed,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
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 {
base_url: String,
shared: Shared,
task: JoinHandle<std::io::Result<()>>,
}
impl Sim {
pub async fn start() -> Self {
Self::start_on(0).await.expect("a loopback port is free")
}
pub async fn start_on(port: u16) -> std::io::Result<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?;
let address = listener.local_addr()?;
let task = tokio::spawn(axum::serve(listener, app).into_future());
Ok(Self {
base_url: format!("http://{address}"),
shared,
task,
})
}
pub fn base_url(&self) -> &str {
&self.base_url
}
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();
}
}
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()
.collect(),
user_agent: request
.headers()
.get(header::USER_AGENT)
.and_then(|value| value.to_str().ok())
.map(str::to_owned),
};
let endpoint = Endpoint::ALL
.into_iter()
.find(|endpoint| endpoint.path() == recorded.path);
let injections = {
let mut inner = lock(&shared);
inner.requests.push(recorded);
inner.injections.clone()
};
for injection in &injections {
if let Injection::Slow(delay) = injection {
tokio::time::sleep(*delay).await;
}
}
let Some(endpoint) = endpoint else {
return json(StatusCode::NOT_FOUND, r#"{"error":"not found"}"#.to_owned());
};
answer(endpoint, &injections)
}
fn answer(endpoint: Endpoint, injections: &[Injection]) -> Response {
let mut body: Value =
serde_json::from_str(endpoint.fixture()).expect("the fixtures are valid JSON");
for injection in injections {
match injection {
Injection::Respond {
endpoint: target,
status,
body,
} if *target == endpoint => {
let status = StatusCode::from_u16(*status).expect("a valid status code");
return json(status, body.clone());
}
Injection::RateLimited {
retry_after_seconds,
} => {
let mut response = json(
StatusCode::TOO_MANY_REQUESTS,
r#"{"error":"too many requests"}"#.to_owned(),
);
response
.headers_mut()
.insert(header::RETRY_AFTER, HeaderValue::from(*retry_after_seconds));
return response;
}
Injection::Malformed => return json(StatusCode::OK, "<html>".to_owned()),
other => modify(&mut body, other),
}
}
json(StatusCode::OK, body.to_string())
}
fn json(status: StatusCode, body: String) -> Response {
(status, [(header::CONTENT_TYPE, "application/json")], body).into_response()
}
fn modify(body: &mut Value, injection: &Injection) {
for_each_trip(body, &mut |trip_id, item| match injection {
Injection::Cancel { trip_id: id } if id == trip_id => cancel(item),
Injection::CancelStop {
trip_id: id,
stop_id,
} if id == trip_id => cancel_stop(item, stop_id),
Injection::Delay {
trip_id: id,
minutes,
} if id == trip_id => delay(item, *minutes),
Injection::NoRealtime => no_realtime(item),
_ => {}
});
}
fn for_each_trip(value: &mut Value, f: &mut impl FnMut(&str, &mut Value)) {
match value {
Value::Object(map) => {
if let Some(trip_id) = map.get("tripId").and_then(Value::as_str) {
let trip_id = trip_id.to_owned();
f(&trip_id, value);
return;
}
for child in map.values_mut() {
for_each_trip(child, f);
}
}
Value::Array(items) => {
for item in items {
for_each_trip(item, f);
}
}
_ => {}
}
}
fn places(item: &mut Value) -> Vec<&mut Value> {
let mut places = Vec::new();
for (key, value) in item.as_object_mut().into_iter().flatten() {
match (key.as_str(), value) {
("from" | "to" | "place" | "tripFrom" | "tripTo", value) => places.push(value),
("intermediateStops", Value::Array(stops)) => places.extend(stops.iter_mut()),
_ => {}
}
}
places
}
fn set_cancelled(place: &mut Value) {
place["cancelled"] = Value::Bool(true);
place["pickupType"] = "NOT_ALLOWED".into();
place["dropoffType"] = "NOT_ALLOWED".into();
}
fn cancel(item: &mut Value) {
item["cancelled"] = Value::Bool(true);
if item.get("place").is_some() {
item["tripCancelled"] = Value::Bool(true);
item["pickupDropoffType"] = "NOT_ALLOWED".into();
}
for place in places(item) {
set_cancelled(place);
}
}
fn cancel_stop(item: &mut Value, stop_id: &str) {
let departs_here = item["place"]["stopId"].as_str() == Some(stop_id);
for place in places(item) {
if place.get("stopId").and_then(Value::as_str) == Some(stop_id) {
set_cancelled(place);
}
}
if departs_here {
item["cancelled"] = Value::Bool(true);
item["pickupDropoffType"] = "NOT_ALLOWED".into();
}
}
fn shift(value: &mut Value, key: &str, minutes: i64) {
let Some(time) = value.get(key).and_then(Value::as_str) else {
return;
};
let time: Timestamp = time.parse().expect("the fixture times are RFC 3339");
let shifted = time + SignedDuration::from_mins(minutes);
value[key] = shifted.to_string().into();
}
fn delay(item: &mut Value, minutes: i64) {
item["realTime"] = Value::Bool(true);
shift(item, "startTime", minutes);
shift(item, "endTime", minutes);
for place in places(item) {
shift(place, "arrival", minutes);
shift(place, "departure", minutes);
for key in ["arrivalTimestampReason", "departureTimestampReason"] {
if place.get(key).is_some() {
place[key] = "PREDICTED".into();
}
}
}
}
fn reset(value: &mut Value, key: &str, scheduled: &str) {
if let Some(time) = value.get(scheduled).cloned() {
value[key] = time;
}
}
fn no_realtime(item: &mut Value) {
item["realTime"] = Value::Bool(false);
reset(item, "startTime", "scheduledStartTime");
reset(item, "endTime", "scheduledEndTime");
for place in places(item) {
reset(place, "arrival", "scheduledArrival");
reset(place, "departure", "scheduledDeparture");
for key in ["arrivalTimestampReason", "departureTimestampReason"] {
if place.get(key).is_some() {
place[key] = "NO_RT_DATA".into();
}
}
}
}