publictransport_client/lib.rs
1//! HTTP client for public transport APIs: EFA, MOTIS, TRIAS, OJP, HAFAS and
2//! `OpenTripPlanner`.
3//!
4//! The [`publictransport`] crate builds requests and parses responses
5//! without doing I/O. This crate sends them with [`reqwest`]. It re-exports
6//! `publictransport` and `reqwest`, so an application depends on this crate
7//! alone. The futures need a Tokio runtime, as all of `reqwest` does.
8//!
9//! ```no_run
10//! use publictransport_client::{
11//! Client, DeparturesQuery, LocationKind, LocationQuery, Network, Protocol, TripsQuery,
12//! };
13//!
14//! # async fn example() -> Result<(), publictransport_client::Error> {
15//! let client = Client::new("my-app/1.0 (+https://example.org)")?;
16//! let vvo = Network::new("vvo", "VVO", "https://efa.vvo-online.de/std3", Protocol::Efa)
17//! .with_timezone("Europe/Berlin");
18//!
19//! // The text alone searches for every kind of location.
20//! let everything = client.locations(&vvo, "Hauptbahnhof").await?;
21//! // A query type carries the options of a request.
22//! let query = LocationQuery::new("Hauptbahnhof").with_kinds([LocationKind::Stop]);
23//! let stops = client.locations(&vvo, query).await?;
24//! println!("{} locations, {} of them stops", everything.len(), stops.len());
25//! if let [from, to, ..] = stops.as_slice() {
26//! for departure in client.departures(&vvo, from).await? {
27//! // The time on the clocks at the stop, where its time zone is known.
28//! if let Some(time) = departure.stop.local_time(departure.scheduled_time) {
29//! println!("{time} {} to {:?}", departure.line.name, departure.direction);
30//! }
31//! }
32//! let board = client.departures(&vvo, DeparturesQuery::new(from).with_limit(5)).await?;
33//! let found = client.trips(&vvo, TripsQuery::new(from, to)).await?;
34//! println!("{} departures, {} trips", board.len(), found.trips.len());
35//! }
36//! # Ok(())
37//! # }
38//! ```
39//!
40//! The client does not retry, limit its request rate or cache. Those are
41//! decisions for the application.
42//!
43//! # Features
44//!
45//! The features choose what `reqwest` is built with. `rustls`, `http2` and
46//! `system-proxy` are on by default.
47//!
48//! - `rustls`: TLS through rustls. Its `aws-lc-rs` provider needs a C
49//! toolchain to build.
50//! - `native-tls`: TLS through the platform's library. Turn the default
51//! features off to use it in place of `rustls`.
52//! - `http2`: HTTP/2.
53//! - `system-proxy`: the proxy that the environment configures.
54//!
55//! Without `rustls` and `native-tls` the client only reaches `http://`
56//! endpoints.
57
58use std::time::Duration;
59
60pub use publictransport::Error as ApiError;
61// The `Error` of this crate takes the place of the one in the glob.
62pub use publictransport::*;
63/// The HTTP client this crate is built on, for [`Client::with_http_client`]
64/// and [`Error::Transport`].
65pub use reqwest;
66
67/// Why a call to a [`Client`] failed.
68#[derive(Debug, thiserror::Error)]
69#[non_exhaustive]
70pub enum Error {
71 /// The HTTP exchange failed: there was no connection, it timed out, TLS
72 /// failed, the answer broke off, or the URL built from
73 /// [`Network::endpoint`] was not valid. [`Client::new`] returns it for a
74 /// client that cannot be built.
75 #[error("the HTTP request failed")]
76 Transport(#[from] reqwest::Error),
77 /// The answer was larger than any real one, so reading it was stopped.
78 #[error("the response is larger than {} MB", MAX_BODY / (1024 * 1024))]
79 TooLarge,
80 /// The request could not be built from the network and the query, or the
81 /// server's answer reports or is a failure.
82 #[error(transparent)]
83 Api(#[from] ApiError),
84}
85
86/// Sends requests to public transport servers. One client serves every
87/// [`Network`] and shares its connections between them.
88#[derive(Debug, Clone)]
89pub struct Client {
90 http: reqwest::Client,
91}
92
93const TIMEOUT: Duration = Duration::from_secs(30);
94
95/// Real answers stay below 1 MB. The limit keeps a broken or hostile server
96/// from filling the memory.
97const MAX_BODY: usize = 16 * 1024 * 1024;
98
99impl Client {
100 /// Creates a client that sends `user_agent` with every request. It
101 /// should name the application, its version and a way to contact its
102 /// authors, e.g. `my-app/1.0 (+https://example.org)`. Some servers,
103 /// such as Transitous, require that.
104 ///
105 /// Requests time out after 30 seconds.
106 ///
107 /// # Errors
108 ///
109 /// Returns [`Error::Transport`] if `user_agent` is not a valid header
110 /// value or the TLS backend cannot be set up.
111 pub fn new(user_agent: &str) -> Result<Self, Error> {
112 let http = reqwest::Client::builder()
113 .user_agent(user_agent)
114 // The core reports a redirect as a moved endpoint.
115 .redirect(reqwest::redirect::Policy::none())
116 .timeout(TIMEOUT)
117 .build()?;
118 Ok(Self { http })
119 }
120
121 /// Creates a client on an HTTP client the caller configured, e.g. with
122 /// a proxy. It must not follow redirects, so that a moved endpoint is
123 /// reported as [`ApiError::Moved`]. It should set a `User-Agent` and a
124 /// timeout, since `reqwest` has none by default.
125 #[must_use]
126 pub fn with_http_client(http: reqwest::Client) -> Self {
127 Self { http }
128 }
129
130 /// Searches for locations by name. The query is the text to search
131 /// for, or a [`LocationQuery`] for a search with options. See
132 /// [`Network::parse_locations`] for the result.
133 ///
134 /// # Errors
135 ///
136 /// Returns [`Error::Transport`] if the request got no answer and
137 /// [`Error::Api`] for everything the server or the query got wrong.
138 pub async fn locations(
139 &self,
140 network: &Network,
141 query: impl Into<LocationQuery>,
142 ) -> Result<Vec<Location>, Error> {
143 let request = network.locations_request(&query.into())?;
144 let response = self.send(request).await?;
145 Ok(network.parse_locations(&response)?)
146 }
147
148 /// Lists the next departures at a stop. The query is the stop, as a
149 /// [`Location`] or as an ID of this network, or a [`DeparturesQuery`]
150 /// for a request with options. A stop that another network returned
151 /// works where this network can name it, see [`Network::stop_id`].
152 /// See
153 /// [`Network::parse_departures`] for the result.
154 ///
155 /// # Errors
156 ///
157 /// Returns [`Error::Transport`] if the request got no answer and
158 /// [`Error::Api`] for everything the server or the query got wrong.
159 pub async fn departures(
160 &self,
161 network: &Network,
162 query: impl Into<DeparturesQuery>,
163 ) -> Result<Vec<Departure>, Error> {
164 let request = network.departures_request(&query.into())?;
165 let response = self.send(request).await?;
166 Ok(network.parse_departures(&response)?)
167 }
168
169 /// Plans trips between two places. The query is a [`TripsQuery`],
170 /// whose ends are locations, coordinates or IDs. See
171 /// [`Network::parse_trips`] for the result. Its references continue the search:
172 ///
173 /// ```no_run
174 /// # use publictransport_client::{Client, Error, Network, TripsQuery};
175 /// # async fn example(client: Client, network: Network, query: TripsQuery) -> Result<(), Error> {
176 /// let mut found = client.trips(&network, &query).await?;
177 /// if let Some(later) = found.later.clone() {
178 /// let more = client.trips(&network, &query.clone().with_page(later)).await?;
179 /// found.trips.extend(more.trips);
180 /// found.later = more.later;
181 /// }
182 /// # Ok(())
183 /// # }
184 /// ```
185 ///
186 /// # Errors
187 ///
188 /// Returns [`Error::Transport`] if the request got no answer and
189 /// [`Error::Api`] for everything the server or the query got wrong.
190 pub async fn trips(
191 &self,
192 network: &Network,
193 query: impl Into<TripsQuery>,
194 ) -> Result<Trips, Error> {
195 let request = network.trips_request(&query.into())?;
196 let response = self.send(request).await?;
197 Ok(network.parse_trips(&response)?)
198 }
199
200 async fn send(&self, request: HttpRequest) -> Result<HttpResponse, Error> {
201 let method = match request.method {
202 Method::Get => reqwest::Method::GET,
203 Method::Post => reqwest::Method::POST,
204 };
205 let mut builder = self.http.request(method, request.url);
206 for header in request.headers {
207 builder = builder.header(header.name, header.value);
208 }
209 if let Some(body) = request.body {
210 builder = builder.body(body);
211 }
212 let mut response = builder.send().await?;
213 let status = response.status().as_u16();
214 let headers = response
215 .headers()
216 .iter()
217 .map(|(name, value)| Header {
218 name: name.as_str().to_owned(),
219 value: String::from_utf8_lossy(value.as_bytes()).into_owned(),
220 })
221 .collect();
222 let mut body = Vec::new();
223 while let Some(chunk) = response.chunk().await? {
224 if body.len() + chunk.len() > MAX_BODY {
225 return Err(Error::TooLarge);
226 }
227 body.extend_from_slice(&chunk);
228 }
229 Ok(HttpResponse {
230 status,
231 headers,
232 body,
233 })
234 }
235}