1use std::fmt;
6use std::sync::Arc;
7
8use jiff::Timestamp;
9use motis::{Client, Geocode, LocationType, Mode, Plan, RealtimeMode, Request, Stoptimes, Trip};
10
11use crate::cache::{self, Cache};
12use crate::config::Config;
13use crate::model::{
14 Attribution, Connection, Departure, DeparturesResult, FindStopResult, JourneyResult, Location,
15 PageCursor, StopMatch, TripResult, UsageSummary,
16};
17use crate::usage::{Endpoint, Usage};
18use crate::{Error, agent, resolve, status};
19
20pub const MAX_CONNECTIONS: u32 = 20;
22pub const MAX_DEPARTURES: u32 = 100;
24pub const MAX_STOPS: u32 = 20;
26const MIN_ARRIVE_BY: u32 = 3;
29const RESOLVE_MATCHES: u32 = 10;
31
32pub type Clock = Arc<dyn Fn() -> Timestamp + Send + Sync>;
34
35pub trait Call: Request {
37 const ENDPOINT: Endpoint;
38}
39
40impl Call for Geocode {
41 const ENDPOINT: Endpoint = Endpoint::Geocode;
42}
43impl Call for motis::ReverseGeocode {
44 const ENDPOINT: Endpoint = Endpoint::ReverseGeocode;
45}
46impl Call for Plan {
47 const ENDPOINT: Endpoint = Endpoint::Plan;
48}
49impl Call for Stoptimes {
50 const ENDPOINT: Endpoint = Endpoint::Stoptimes;
51}
52impl Call for Trip {
53 const ENDPOINT: Endpoint = Endpoint::Trip;
54}
55
56#[derive(Debug, Clone, Default, PartialEq)]
58pub struct StopsQuery {
59 pub text: String,
60 pub near: Option<(f64, f64)>,
62 pub count: u32,
64}
65
66#[derive(Debug, Clone, Default, PartialEq, Eq)]
68pub struct DeparturesQuery {
69 pub stop: String,
71 pub time: Option<Timestamp>,
73 pub count: u32,
76 pub arrivals: bool,
77 pub modes: Vec<Mode>,
79 pub page_cursor: Option<String>,
80}
81
82#[derive(Debug, Clone, Default, PartialEq, Eq)]
84#[allow(clippy::struct_excessive_bools, reason = "independent options")]
85pub struct TripQuery {
86 pub from: String,
88 pub to: String,
89 pub time: Option<Timestamp>,
91 pub arrive_by: bool,
94 pub count: u32,
98 pub modes: Vec<Mode>,
100 pub max_transfers: Option<u32>,
101 pub page_cursor: Option<String>,
102 pub realtime_routing: bool,
105}
106
107#[derive(Clone)]
109pub struct Transitous {
110 client: Client,
111 cache: Cache,
112 usage: Usage,
113 delay_threshold_minutes: u32,
114 clock: Clock,
115}
116
117impl fmt::Debug for Transitous {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119 f.debug_struct("Transitous")
120 .field("client", &self.client)
121 .field("cache", &self.cache)
122 .field("usage", &self.usage)
123 .finish_non_exhaustive()
124 }
125}
126
127impl Transitous {
128 pub fn new(config: &Config, product: &str) -> Result<Self, Error> {
134 let user_agent = agent::user_agent(product, config.contact.as_deref())?;
135 let client = Client::builder(&config.base_url)
136 .user_agent(user_agent)
137 .timeout(config.timeout)
138 .build()?;
139 Ok(Self {
140 client,
141 cache: Cache::new(config.cache_dir.clone()),
142 usage: Usage::new(config.state_dir.as_deref(), config.plan_daily_limit),
143 delay_threshold_minutes: config.delay_threshold_minutes,
144 clock: Arc::new(Timestamp::now),
145 })
146 }
147
148 #[must_use]
150 pub fn with_clock(mut self, clock: Clock) -> Self {
151 self.clock = clock;
152 self
153 }
154
155 pub fn usage(&self) -> &Usage {
157 &self.usage
158 }
159
160 pub fn usage_summary(&self) -> Result<UsageSummary, Error> {
162 self.usage.summary((self.clock)())
163 }
164
165 async fn call<R: Call>(
167 &self,
168 request: &R,
169 warnings: &mut Vec<String>,
170 ) -> Result<R::Response, Error> {
171 let key = self.client.url(request).to_string();
172 let now = (self.clock)();
173 let cached = self
174 .cache
175 .get(&key, cache::ttl(R::ENDPOINT), now)
176 .and_then(|body| Client::decode::<R>(&body).ok());
177 if let Some(response) = cached {
178 return Ok(response);
179 }
180 warnings.extend(self.usage.admit(R::ENDPOINT, now)?);
181 let body = self.client.fetch(request).await?;
182 let response = Client::decode::<R>(&body)?;
183 self.cache.put(&key, &body, now);
184 Ok(response)
185 }
186
187 pub async fn find_stops(&self, query: &StopsQuery) -> Result<FindStopResult, Error> {
189 let mut warnings = Vec::new();
190 let request = Geocode {
191 types: vec![LocationType::Stop],
192 place: query.near.map(|(lat, lon)| format!("{lat},{lon}")),
193 num_results: Some(query.count.clamp(1, MAX_STOPS)),
194 ..Geocode::new(query.text.clone())
195 };
196 let matches = self.call(&request, &mut warnings).await?;
197 Ok(FindStopResult {
198 query: query.text.clone(),
199 stops: matches
200 .iter()
201 .filter(|found| found.kind == LocationType::Stop)
202 .map(StopMatch::from)
203 .collect(),
204 attribution: Attribution::default(),
205 warnings,
206 })
207 }
208
209 pub async fn resolve_stop(
211 &self,
212 input: &str,
213 warnings: &mut Vec<String>,
214 ) -> Result<String, Error> {
215 let input = input.trim();
216 if resolve::is_stop_id(input) {
217 return Ok(input.to_owned());
218 }
219 if input.is_empty() {
220 return Err(Error::StopNotFound {
221 query: input.to_owned(),
222 });
223 }
224 let request = Geocode {
225 types: vec![LocationType::Stop],
226 num_results: Some(RESOLVE_MATCHES),
227 ..Geocode::new(input)
228 };
229 let matches = self.call(&request, warnings).await?;
230 Ok(resolve::choose(input, &matches)?.id.clone())
231 }
232
233 async fn resolve_place(
235 &self,
236 input: &str,
237 warnings: &mut Vec<String>,
238 ) -> Result<String, Error> {
239 match resolve::coordinates(input) {
240 Some((lat, lon)) => Ok(format!("{lat},{lon}")),
241 None => self.resolve_stop(input, warnings).await,
242 }
243 }
244
245 pub async fn departures(&self, query: &DeparturesQuery) -> Result<DeparturesResult, Error> {
247 let mut warnings = Vec::new();
248 let stop_id = self.resolve_stop(&query.stop, &mut warnings).await?;
249 let request = Stoptimes {
250 time: query.time,
251 arrive_by: Some(query.arrivals),
252 n: Some(query.count.clamp(1, MAX_DEPARTURES)),
253 mode: query.modes.clone(),
254 page_cursor: query.page_cursor.clone(),
255 with_alerts: Some(true),
256 ..Stoptimes::new(stop_id.clone())
257 };
258 let response = self.call(&request, &mut warnings).await?;
259 let mut stop = Location::from(&response.place);
260 stop.id.get_or_insert(stop_id);
261 Ok(DeparturesResult {
262 stop,
263 arrivals: query.arrivals,
264 departures: response
265 .stop_times
266 .iter()
267 .map(|stop_time| Departure::new(stop_time, query.arrivals))
268 .collect(),
269 page_cursor: PageCursor::new(
270 &response.previous_page_cursor,
271 &response.next_page_cursor,
272 ),
273 attribution: Attribution::default(),
274 warnings,
275 })
276 }
277
278 pub async fn trip(&self, query: &TripQuery) -> Result<TripResult, Error> {
284 let mut warnings = Vec::new();
285 let from = self.resolve_place(&query.from, &mut warnings).await?;
286 let to = self.resolve_place(&query.to, &mut warnings).await?;
287 let count = query.count.clamp(1, MAX_CONNECTIONS);
288 let wanted = if query.arrive_by {
289 count.max(MIN_ARRIVE_BY)
290 } else {
291 count
292 };
293 let now = (self.clock)();
294 let request = Plan {
295 time: query.time.or(query.arrive_by.then_some(now)),
296 arrive_by: Some(query.arrive_by),
297 num_itineraries: Some(wanted),
298 page_cursor: query.page_cursor.clone(),
299 transit_modes: query.modes.clone(),
300 max_transfers: query.max_transfers,
301 realtime_mode: Some(if query.realtime_routing {
302 RealtimeMode::Realtime
303 } else {
304 RealtimeMode::RealtimeAnnotationOnly
305 }),
306 ..Plan::new(from, to)
307 };
308 let response = self.call(&request, &mut warnings).await?;
309 let mut itineraries = response.itineraries;
312 add_new(&mut itineraries, response.direct);
313 let mut earlier = response.previous_page_cursor;
314 let later = response.next_page_cursor;
315 let short = itineraries.len() < count as usize;
316 if query.arrive_by && query.page_cursor.is_none() && short && !earlier.is_empty() {
317 let previous = Plan {
318 page_cursor: Some(earlier.clone()),
319 ..request
320 };
321 match self.call(&previous, &mut warnings).await {
322 Ok(page) => {
323 earlier = page.previous_page_cursor;
324 add_new(&mut itineraries, page.itineraries);
325 }
326 Err(error) => warnings.push(format!("no earlier connections: {error}")),
327 }
328 }
329 itineraries.sort_by_key(departure);
330 let now = (self.clock)();
331 Ok(TripResult {
332 from: Location::from(&response.from),
333 to: Location::from(&response.to),
334 connections: itineraries
335 .iter()
336 .map(|itinerary| {
337 let evaluation = status::evaluate(itinerary, now, self.delay_threshold_minutes);
338 Connection::new(itinerary, evaluation)
339 })
340 .collect(),
341 page_cursor: PageCursor::new(&earlier, &later),
342 attribution: Attribution::default(),
343 warnings,
344 })
345 }
346
347 pub async fn journey(&self, trip_id: &str) -> Result<JourneyResult, Error> {
349 let mut warnings = Vec::new();
350 let itinerary = self.call(&Trip::new(trip_id), &mut warnings).await?;
351 Ok(JourneyResult::new(trip_id, &itinerary, warnings))
352 }
353}
354
355fn departure(itinerary: &motis::Itinerary) -> Timestamp {
358 itinerary
359 .legs
360 .first()
361 .map_or(itinerary.start_time, |leg| leg.scheduled_start_time)
362}
363
364fn add_new(known: &mut Vec<motis::Itinerary>, page: Vec<motis::Itinerary>) {
367 for itinerary in page {
368 if !known.iter().any(|other| same(other, &itinerary)) {
369 known.push(itinerary);
370 }
371 }
372}
373
374fn same(a: &motis::Itinerary, b: &motis::Itinerary) -> bool {
375 if !a.id.is_empty() && !b.id.is_empty() {
376 return a.id == b.id;
377 }
378 let trips = |it: &motis::Itinerary| -> Vec<(Option<String>, Timestamp)> {
379 it.legs
380 .iter()
381 .map(|leg| (leg.trip_id.clone(), leg.scheduled_start_time))
382 .collect()
383 };
384 trips(a) == trips(b)
385}
386
387#[cfg(test)]
388mod tests {
389 use super::*;
390
391 #[test]
392 fn tells_connections_apart() {
393 let leg = |trip: &str, minute: i64| motis::Leg {
394 trip_id: Some(trip.into()),
395 scheduled_start_time: Timestamp::from_second(minute * 60).unwrap(),
396 ..motis::Leg::default()
397 };
398 let with = |id: &str, legs| motis::Itinerary {
399 id: id.into(),
400 legs,
401 ..motis::Itinerary::default()
402 };
403 assert!(same(&with("a", vec![]), &with("a", vec![leg("x", 1)])));
404 assert!(!same(&with("a", vec![]), &with("b", vec![])));
405 assert!(same(
406 &with("", vec![leg("x", 1)]),
407 &with("", vec![leg("x", 1)])
408 ));
409 assert!(!same(
410 &with("", vec![leg("x", 1)]),
411 &with("a", vec![leg("x", 2)])
412 ));
413 assert_eq!(departure(&with("", vec![])), Timestamp::default());
414 let mut known = vec![with("a", vec![]), with("b", vec![])];
415 add_new(&mut known, vec![with("b", vec![]), with("c", vec![])]);
416 let ids: Vec<&str> = known.iter().map(|i| i.id.as_str()).collect();
417 assert_eq!(ids, ["a", "b", "c"]);
418 }
419}