1use std::future::IntoFuture;
22use std::sync::{Arc, Mutex, MutexGuard};
23use std::time::Duration;
24
25use axum::Router;
26use axum::extract::{Request, State};
27use axum::http::{HeaderValue, StatusCode, header};
28use axum::response::{IntoResponse, Response};
29use jiff::{SignedDuration, Timestamp};
30use serde_json::Value;
31use tokio::task::JoinHandle;
32
33pub const DIRECT_TRIP: &str = "20261126_20:59_de-DELFI_3490143191";
36
37pub const DEPARTURE_TRIP: &str = "20261126_20:33_de-DELFI_3031893234";
39
40pub const FEEDER_TRIP: &str = "20261126_21:20_de-DELFI_3031889606";
43
44pub const CONNECTING_TRIP: &str = "20261126_21:25_de-DELFI_3126800675";
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50#[non_exhaustive]
51pub enum Endpoint {
52 Plan,
53 Stoptimes,
54 Trip,
55 Geocode,
56 ReverseGeocode,
57}
58
59impl Endpoint {
60 const ALL: [Self; 5] = [
61 Self::Plan,
62 Self::Stoptimes,
63 Self::Trip,
64 Self::Geocode,
65 Self::ReverseGeocode,
66 ];
67
68 pub fn path(self) -> &'static str {
70 match self {
71 Self::Plan => "/api/v6/plan",
72 Self::Stoptimes => "/api/v6/stoptimes",
73 Self::Trip => "/api/v6/trip",
74 Self::Geocode => "/api/v1/geocode",
75 Self::ReverseGeocode => "/api/v1/reverse-geocode",
76 }
77 }
78
79 fn fixture(self) -> &'static str {
80 match self {
81 Self::Plan => include_str!("../fixtures/plan.json"),
82 Self::Stoptimes => include_str!("../fixtures/stoptimes.json"),
83 Self::Trip => include_str!("../fixtures/trip.json"),
84 Self::Geocode => include_str!("../fixtures/geocode.json"),
85 Self::ReverseGeocode => include_str!("../fixtures/reverse-geocode.json"),
86 }
87 }
88}
89
90#[derive(Debug, Clone, PartialEq)]
93#[non_exhaustive]
94pub enum Injection {
95 Cancel { trip_id: String },
97 CancelStop { trip_id: String, stop_id: String },
99 Delay { trip_id: String, minutes: i64 },
101 NoRealtime,
103 Respond {
105 endpoint: Endpoint,
106 status: u16,
107 body: String,
108 },
109 RateLimited { retry_after_seconds: u64 },
111 Slow(Duration),
113 Malformed,
115}
116
117#[derive(Debug, Clone, PartialEq, Eq)]
119#[non_exhaustive]
120pub struct Recorded {
121 pub path: String,
122 pub query: Vec<(String, String)>,
124 pub user_agent: Option<String>,
125}
126
127impl Recorded {
128 pub fn param(&self, name: &str) -> Option<&str> {
130 self.query
131 .iter()
132 .find(|(key, _)| key == name)
133 .map(|(_, value)| value.as_str())
134 }
135}
136
137#[derive(Debug, Default)]
138struct Inner {
139 injections: Vec<Injection>,
140 requests: Vec<Recorded>,
141}
142
143type Shared = Arc<Mutex<Inner>>;
144
145fn lock(shared: &Shared) -> MutexGuard<'_, Inner> {
146 shared
147 .lock()
148 .unwrap_or_else(std::sync::PoisonError::into_inner)
149}
150
151#[derive(Debug)]
153pub struct Sim {
154 base_url: String,
155 shared: Shared,
156 task: JoinHandle<std::io::Result<()>>,
157}
158
159impl Sim {
160 pub async fn start() -> Self {
166 Self::start_on(0).await.expect("a loopback port is free")
167 }
168
169 pub async fn start_on(port: u16) -> std::io::Result<Self> {
172 let shared = Shared::default();
173 let app = Router::new()
174 .fallback(handle)
175 .with_state(Arc::clone(&shared));
176 let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await?;
177 let address = listener.local_addr()?;
178 let task = tokio::spawn(axum::serve(listener, app).into_future());
179 Ok(Self {
180 base_url: format!("http://{address}"),
181 shared,
182 task,
183 })
184 }
185
186 pub fn base_url(&self) -> &str {
188 &self.base_url
189 }
190
191 pub fn inject(&self, injection: Injection) {
192 lock(&self.shared).injections.push(injection);
193 }
194
195 pub fn clear(&self) {
197 lock(&self.shared).injections.clear();
198 }
199
200 pub fn requests(&self) -> Vec<Recorded> {
202 lock(&self.shared).requests.clone()
203 }
204}
205
206impl Drop for Sim {
207 fn drop(&mut self) {
208 self.task.abort();
209 }
210}
211
212async fn handle(State(shared): State<Shared>, request: Request) -> Response {
213 let uri = request.uri();
214 let recorded = Recorded {
215 path: uri.path().to_owned(),
216 query: form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes())
217 .into_owned()
218 .collect(),
219 user_agent: request
220 .headers()
221 .get(header::USER_AGENT)
222 .and_then(|value| value.to_str().ok())
223 .map(str::to_owned),
224 };
225 let endpoint = Endpoint::ALL
226 .into_iter()
227 .find(|endpoint| endpoint.path() == recorded.path);
228 let injections = {
229 let mut inner = lock(&shared);
230 inner.requests.push(recorded);
231 inner.injections.clone()
232 };
233 for injection in &injections {
234 if let Injection::Slow(delay) = injection {
235 tokio::time::sleep(*delay).await;
236 }
237 }
238 let Some(endpoint) = endpoint else {
239 return json(StatusCode::NOT_FOUND, r#"{"error":"not found"}"#.to_owned());
240 };
241 answer(endpoint, &injections)
242}
243
244fn answer(endpoint: Endpoint, injections: &[Injection]) -> Response {
245 let mut body: Value =
246 serde_json::from_str(endpoint.fixture()).expect("the fixtures are valid JSON");
247 for injection in injections {
248 match injection {
249 Injection::Respond {
250 endpoint: target,
251 status,
252 body,
253 } if *target == endpoint => {
254 let status = StatusCode::from_u16(*status).expect("a valid status code");
255 return json(status, body.clone());
256 }
257 Injection::RateLimited {
258 retry_after_seconds,
259 } => {
260 let mut response = json(
261 StatusCode::TOO_MANY_REQUESTS,
262 r#"{"error":"too many requests"}"#.to_owned(),
263 );
264 response
265 .headers_mut()
266 .insert(header::RETRY_AFTER, HeaderValue::from(*retry_after_seconds));
267 return response;
268 }
269 Injection::Malformed => return json(StatusCode::OK, "<html>".to_owned()),
270 other => modify(&mut body, other),
271 }
272 }
273 json(StatusCode::OK, body.to_string())
274}
275
276fn json(status: StatusCode, body: String) -> Response {
277 (status, [(header::CONTENT_TYPE, "application/json")], body).into_response()
278}
279
280fn modify(body: &mut Value, injection: &Injection) {
282 for_each_trip(body, &mut |trip_id, item| match injection {
283 Injection::Cancel { trip_id: id } if id == trip_id => cancel(item),
284 Injection::CancelStop {
285 trip_id: id,
286 stop_id,
287 } if id == trip_id => cancel_stop(item, stop_id),
288 Injection::Delay {
289 trip_id: id,
290 minutes,
291 } if id == trip_id => delay(item, *minutes),
292 Injection::NoRealtime => no_realtime(item),
293 _ => {}
294 });
295}
296
297fn for_each_trip(value: &mut Value, f: &mut impl FnMut(&str, &mut Value)) {
299 match value {
300 Value::Object(map) => {
301 if let Some(trip_id) = map.get("tripId").and_then(Value::as_str) {
302 let trip_id = trip_id.to_owned();
303 f(&trip_id, value);
304 return;
305 }
306 for child in map.values_mut() {
307 for_each_trip(child, f);
308 }
309 }
310 Value::Array(items) => {
311 for item in items {
312 for_each_trip(item, f);
313 }
314 }
315 _ => {}
316 }
317}
318
319fn places(item: &mut Value) -> Vec<&mut Value> {
323 let mut places = Vec::new();
324 for (key, value) in item.as_object_mut().into_iter().flatten() {
325 match (key.as_str(), value) {
326 ("from" | "to" | "place" | "tripFrom" | "tripTo", value) => places.push(value),
327 ("intermediateStops", Value::Array(stops)) => places.extend(stops.iter_mut()),
328 _ => {}
329 }
330 }
331 places
332}
333
334fn set_cancelled(place: &mut Value) {
335 place["cancelled"] = Value::Bool(true);
336 place["pickupType"] = "NOT_ALLOWED".into();
337 place["dropoffType"] = "NOT_ALLOWED".into();
338}
339
340fn cancel(item: &mut Value) {
341 item["cancelled"] = Value::Bool(true);
342 if item.get("place").is_some() {
343 item["tripCancelled"] = Value::Bool(true);
344 item["pickupDropoffType"] = "NOT_ALLOWED".into();
345 }
346 for place in places(item) {
347 set_cancelled(place);
348 }
349}
350
351fn cancel_stop(item: &mut Value, stop_id: &str) {
352 let departs_here = item["place"]["stopId"].as_str() == Some(stop_id);
354 for place in places(item) {
355 if place.get("stopId").and_then(Value::as_str) == Some(stop_id) {
356 set_cancelled(place);
357 }
358 }
359 if departs_here {
360 item["cancelled"] = Value::Bool(true);
361 item["pickupDropoffType"] = "NOT_ALLOWED".into();
362 }
363}
364
365fn shift(value: &mut Value, key: &str, minutes: i64) {
367 let Some(time) = value.get(key).and_then(Value::as_str) else {
368 return;
369 };
370 let time: Timestamp = time.parse().expect("the fixture times are RFC 3339");
371 let shifted = time + SignedDuration::from_mins(minutes);
372 value[key] = shifted.to_string().into();
373}
374
375fn delay(item: &mut Value, minutes: i64) {
376 item["realTime"] = Value::Bool(true);
377 shift(item, "startTime", minutes);
378 shift(item, "endTime", minutes);
379 for place in places(item) {
380 shift(place, "arrival", minutes);
381 shift(place, "departure", minutes);
382 for key in ["arrivalTimestampReason", "departureTimestampReason"] {
383 if place.get(key).is_some() {
384 place[key] = "PREDICTED".into();
385 }
386 }
387 }
388}
389
390fn reset(value: &mut Value, key: &str, scheduled: &str) {
392 if let Some(time) = value.get(scheduled).cloned() {
393 value[key] = time;
394 }
395}
396
397fn no_realtime(item: &mut Value) {
398 item["realTime"] = Value::Bool(false);
399 reset(item, "startTime", "scheduledStartTime");
400 reset(item, "endTime", "scheduledEndTime");
401 for place in places(item) {
402 reset(place, "arrival", "scheduledArrival");
403 reset(place, "departure", "scheduledDeparture");
404 for key in ["arrivalTimestampReason", "departureTimestampReason"] {
405 if place.get(key).is_some() {
406 place[key] = "NO_RT_DATA".into();
407 }
408 }
409 }
410}