valhalla-client 0.5.1

API client for the Valhalla routing engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))]

/// [`costing`] model-configuration for different transport modes
pub mod costing;
/// Models connected to the [`elevation`]-api
pub mod elevation;
/// Models connected to the Time-distance [`matrix`]-api
pub mod matrix;
/// Models connected to the Turn-by-turn [`route`]ing-api
pub mod route;
/// Shape decoding support for [`route`] and [`elevation`]
pub mod shapes;
/// Models connected to the healthcheck via the [`status`]-API
pub mod status;
/// Models connected to the [`trace_attributes`] map-matching API
pub mod trace_attributes;

use log::trace;
use serde::{Deserialize, Serialize};

/// A longitude, latitude coordinate in degrees
///
/// See <https://en.wikipedia.org/wiki/Geographic_coordinate_system> for further context
pub type Coordinate = (f32, f32);
impl From<Coordinate> for shapes::ShapePoint {
    fn from((lon, lat): Coordinate) -> Self {
        Self {
            lon: lon as f64,
            lat: lat as f64,
        }
    }
}

#[derive(Deserialize, Debug, Clone)]
/// A description with a code
pub struct CodedDescription {
    /// A code
    pub code: u64,

    /// A human-readable description
    pub description: String,
}

/// valhalla needs `date_time` fields to be in the `YYYY-MM-DDTHH:MM` format
pub(crate) fn serialize_naive_date_time_opt<S>(
    value: &Option<chrono::NaiveDateTime>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    match value {
        None => serializer.serialize_none(),
        Some(value) => serialize_naive_date_time(value, serializer),
    }
}

/// valhalla needs `date_time` fields to be in the `YYYY-MM-DDTHH:MM` format
fn serialize_naive_date_time<S>(
    value: &chrono::NaiveDateTime,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    serializer.serialize_str(&value.format("%Y-%m-%dT%H:%M").to_string())
}

#[derive(Serialize, Deserialize, Default, Debug, Clone, Copy, PartialEq, Eq)]
/// The units used for the response
pub enum Units {
    #[default]
    #[serde(rename = "kilometers")]
    /// Metric units
    Metric,

    #[serde(rename = "miles")]
    /// Imperial units
    Imperial,
}
/// The local date and time at the location
#[derive(Serialize, Debug)]
pub struct DateTime {
    r#type: MatrixDateTimeType,
    #[serde(serialize_with = "serialize_naive_date_time")]
    value: chrono::NaiveDateTime,
}

impl DateTime {
    /// Current departure time
    pub fn from_current_departure_time() -> Self {
        Self {
            r#type: MatrixDateTimeType::CurrentDeparture,
            value: chrono::Local::now().naive_local(),
        }
    }
    /// Specified departure time
    pub fn from_departure_time(depart_after: chrono::NaiveDateTime) -> Self {
        Self {
            r#type: MatrixDateTimeType::SpecifiedDeparture,
            value: depart_after,
        }
    }
    /// Specified arrival time
    pub fn from_arrival_time(arrive_by: chrono::NaiveDateTime) -> Self {
        Self {
            r#type: MatrixDateTimeType::SpecifiedArrival,
            value: arrive_by,
        }
    }
}

#[derive(serde_repr::Serialize_repr, Debug, Clone, Copy)]
#[repr(u8)]
enum MatrixDateTimeType {
    CurrentDeparture = 0,
    SpecifiedDeparture,
    SpecifiedArrival,
}

#[derive(Debug)]
/// An error that can occur when using the Valhalla API
pub enum Error {
    /// An error from the reqwest library
    Reqwest(reqwest::Error),

    /// An error from the url library
    Url(url::ParseError),

    /// An error from the serde library
    Serde(serde_json::Error),

    /// An error from the remote API
    RemoteError(RemoteError),
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Reqwest(e) => write!(f, "reqwest error: {e}"),
            Self::Url(e) => write!(f, "url error: {e}"),
            Self::Serde(e) => write!(f, "serde error: {e}"),
            Self::RemoteError(e) => write!(f, "remote error: {e:?}"),
        }
    }
}

impl std::error::Error for Error {}

#[derive(Debug, Deserialize)]
/// An error response from the Valhalla API
pub struct RemoteError {
    /// An error code
    pub error_code: isize,

    /// A human-readable error message
    pub error: String,

    /// HTTP status code
    pub status_code: isize,

    /// HTTP status message
    pub status: String,
}

/// synchronous ("blocking") client implementation
#[cfg(feature = "blocking")]
pub mod blocking {
    use crate::{
        elevation, matrix, route, status, trace_attributes, Error, VALHALLA_PUBLIC_API_URL,
    };
    use std::sync::Arc;

    #[derive(Debug, Clone)]
    /// A synchronous client for the Valhalla API
    pub struct Valhalla {
        runtime: Arc<tokio::runtime::Runtime>,
        client: super::Valhalla,
    }
    impl Valhalla {
        /// Create a sync [Valhalla](https://valhalla.github.io/valhalla/) client
        pub fn new(base_url: url::Url) -> Self {
            Self::with_client(base_url.clone(), reqwest::Client::new())
        }

        /// Create a sync client with a custom [reqwest::Client].
        ///
        /// This allows configuring timeouts, user-agents, proxies, etc.
        pub fn with_client(base_url: url::Url, client: reqwest::Client) -> Self {
            let runtime = tokio::runtime::Builder::new_current_thread()
                .enable_io()
                .enable_time()
                .build()
                .expect("tokio runtime can be created");
            Self {
                runtime: Arc::new(runtime),
                client: super::Valhalla::with_client(base_url, client),
            }
        }

        /// Make a turn-by-turn routing request
        ///
        /// See <https://valhalla.github.io/valhalla/api/turn-by-turn/api-reference> for details
        ///
        /// # Example:
        /// ```rust,no_run
        /// use valhalla_client::blocking::Valhalla;
        /// use valhalla_client::route::{Location, Manifest,};
        /// use valhalla_client::costing::Costing;
        ///
        /// let amsterdam = Location::new(4.9041, 52.3676);
        /// let utrecht = Location::new(5.1214, 52.0907);
        ///
        /// let manifest = Manifest::builder()
        ///   .locations([utrecht,amsterdam])
        ///   .alternates(2)
        ///   .costing(Costing::Auto(Default::default()))
        ///   .language("de-De");
        ///
        /// let response = Valhalla::default().route(manifest).unwrap();
        /// # use valhalla_client::matrix::Response;
        /// # assert!(response.warnings.is_none());
        /// # assert_eq!(response.locations.len(), 2);
        /// ```
        pub fn route(&self, manifest: route::Manifest) -> Result<route::Trip, Error> {
            self.runtime
                .block_on(async move { self.client.route(manifest).await })
        }
        /// Make a time-distance matrix routing request
        ///
        /// See <https://valhalla.github.io/valhalla/api/matrix/api-reference> for details
        ///
        /// # Example:
        /// ```rust,no_run
        /// use valhalla_client::blocking::Valhalla;
        /// use valhalla_client::matrix::{DateTime, Location, Manifest,};
        /// use valhalla_client::costing::Costing;
        ///
        /// let amsterdam = Location::new(4.9041, 52.3676);
        /// let utrecht = Location::new(5.1214, 52.0907);
        /// let rotterdam = Location::new(4.4775302894411, 51.92485867761482);
        /// let den_haag = Location::new(4.324908478055228, 52.07934071633195);
        ///
        /// let manifest = Manifest::builder()
        ///   .verbose_output(true)
        ///   .sources_to_targets([utrecht],[amsterdam,rotterdam,den_haag])
        ///   .date_time(DateTime::from_departure_time(chrono::Local::now().naive_local()))
        ///   .costing(Costing::Auto(Default::default()));
        ///
        /// let response = Valhalla::default()
        ///   .matrix(manifest)
        ///   .unwrap();
        /// # use valhalla_client::matrix::Response;
        /// # if let Response::Verbose(r) = response{
        /// #   assert!(r.warnings.is_empty());
        /// #   assert_eq!(r.sources.len(),1);
        /// #   assert_eq!(r.targets.len(),3);
        /// # };
        /// ```
        pub fn matrix(&self, manifest: matrix::Manifest) -> Result<matrix::Response, Error> {
            self.runtime
                .block_on(async move { self.client.matrix(manifest).await })
        }
        /// Make an elevation request
        ///
        /// Valhalla's elevation lookup service provides digital elevation model (DEM) data as the result of a query.
        /// The elevation service data has many applications when combined with other routing and navigation data, including computing the steepness of roads and paths or generating an elevation profile chart along a route.
        ///
        /// For example, you can get elevation data for a point, a trail, or a trip.
        /// You might use the results to consider hills for your bicycle trip, or when estimating battery usage for trips in electric vehicles.
        ///
        /// See <https://valhalla.github.io/valhalla/api/elevation/api-reference/> for details
        ///
        /// # Example:
        ///
        /// ```rust,no_run
        /// use valhalla_client::blocking::Valhalla;
        /// use valhalla_client::elevation::Manifest;
        ///
        /// let request = Manifest::builder()
        ///   .shape([
        ///     (40.712431, -76.504916),
        ///     (40.712275, -76.605259),
        ///     (40.712122, -76.805694),
        ///     (40.722431, -76.884916),
        ///     (40.812275, -76.905259),
        ///     (40.912122, -76.965694),
        ///   ])
        ///   .include_range();
        /// let response = Valhalla::default()
        ///   .elevation(request).unwrap();
        /// # assert!(response.height.is_empty());
        /// # assert_eq!(response.range_height.len(), 6);
        /// # assert!(response.encoded_polyline.is_none());
        /// # assert!(response.warnings.is_empty());
        /// # assert_eq!(response.x_coordinate, None);
        /// # assert_eq!(response.y_coordinate, None);
        /// # assert_eq!(response.shape.map(|s|s.len()),Some(6));
        /// ```
        pub fn elevation(
            &self,
            manifest: elevation::Manifest,
        ) -> Result<elevation::Response, Error> {
            self.runtime
                .block_on(async move { self.client.elevation(manifest).await })
        }
        /// Make a status request
        ///
        /// This can be used as a health endpoint for the HTTP API or to toggle features in a frontend.
        ///
        /// See <https://valhalla.github.io/valhalla/api/status/api-reference/> for details
        ///
        /// # Example:
        /// ```rust,no_run
        /// use valhalla_client::blocking::Valhalla;
        /// use valhalla_client::status::Manifest;
        ///
        /// let request = Manifest::builder()
        ///   .verbose_output(false);
        /// let response = Valhalla::default()
        ///   .status(request).unwrap();
        /// # assert!(response.version >= semver::Version::parse("3.1.4").unwrap());
        /// # assert!(response.tileset_last_modified.timestamp() > 0);
        /// # assert!(response.verbose.is_none());
        /// ```
        pub fn status(&self, manifest: status::Manifest) -> Result<status::Response, Error> {
            self.runtime
                .block_on(async move { self.client.status(manifest).await })
        }

        /// Make a trace_attributes request for map matching with edge attributes
        ///
        /// See <https://valhalla.github.io/valhalla/api/map-matching/api-reference/> for details
        ///
        /// # Example:
        /// ```rust,no_run
        /// use valhalla_client::blocking::Valhalla;
        /// use valhalla_client::trace_attributes::{Manifest, TracePoint};
        /// use valhalla_client::costing::Costing;
        ///
        /// let manifest = Manifest::builder(
        ///   [TracePoint::new(52.3676, 4.9041), TracePoint::new(52.0907, 5.1214)],
        ///   Costing::Auto(Default::default()),
        /// )
        /// .include_attributes(["edge.surface", "edge.road_class", "edge.length"]);
        ///
        /// let response = Valhalla::default()
        ///   .trace_attributes(manifest).unwrap();
        /// # assert!(!response.edges.is_empty());
        /// ```
        pub fn trace_attributes(
            &self,
            manifest: trace_attributes::Manifest,
        ) -> Result<trace_attributes::Response, Error> {
            self.runtime
                .block_on(async move { self.client.trace_attributes(manifest).await })
        }
    }
    impl Default for Valhalla {
        fn default() -> Self {
            Self::new(
                url::Url::parse(VALHALLA_PUBLIC_API_URL)
                    .expect("VALHALLA_PUBLIC_API_URL is not a valid url"),
            )
        }
    }
}

/// The default public Valhalla API URL hosted by OpenStreetMap Germany.
pub const VALHALLA_PUBLIC_API_URL: &str = "https://valhalla1.openstreetmap.de/";
#[derive(Debug, Clone)]
/// async Valhalla client
pub struct Valhalla {
    client: reqwest::Client,
    base_url: url::Url,
}

impl Valhalla {
    /// Create an async [Valhalla](https://valhalla.github.io/valhalla/) client
    pub fn new(base_url: url::Url) -> Self {
        Self::with_client(base_url, reqwest::Client::new())
    }

    /// Create an async client with a custom [reqwest::Client].
    ///
    /// This allows configuring timeouts, user-agents, proxies, etc.
    pub fn with_client(base_url: url::Url, client: reqwest::Client) -> Self {
        Self { client, base_url }
    }

    /// Make a turn-by-turn routing request
    ///
    /// See <https://valhalla.github.io/valhalla/api/turn-by-turn/api-reference> for details
    ///
    /// # Example:
    /// ```rust
    /// # async fn route(){
    /// use valhalla_client::Valhalla;
    /// use valhalla_client::route::{Location, Manifest,};
    /// use valhalla_client::costing::Costing;
    ///
    /// let amsterdam = Location::new(4.9041, 52.3676);
    /// let utrecht = Location::new(5.1214, 52.0907);
    ///
    /// let manifest = Manifest::builder()
    ///   .locations([utrecht,amsterdam])
    ///   .alternates(2)
    ///   .costing(Costing::Auto(Default::default()))
    ///   .language("de-De");
    ///
    /// let response = Valhalla::default().route(manifest).await.unwrap();
    /// # assert!(response.warnings.is_none());
    /// # assert_eq!(response.locations.len(), 2);
    /// # }
    /// ```
    pub async fn route(&self, manifest: route::Manifest) -> Result<route::Trip, Error> {
        let response: route::Response = self.do_request(manifest, "route", "route").await?;
        Ok(response.trip)
    }

    /// Make a time-distance matrix routing request
    ///
    /// See <https://valhalla.github.io/valhalla/api/matrix/api-reference> for details
    ///
    /// # Example:
    /// ```rust
    /// # async fn matrix(){
    /// use valhalla_client::Valhalla;
    /// use valhalla_client::matrix::{DateTime, Location, Manifest,};
    /// use valhalla_client::costing::Costing;
    ///
    /// let amsterdam = Location::new(4.9041, 52.3676);
    /// let utrecht = Location::new(5.1214, 52.0907);
    /// let rotterdam = Location::new(4.4775302894411, 51.92485867761482);
    /// let den_haag = Location::new(4.324908478055228, 52.07934071633195);
    ///
    /// let manifest = Manifest::builder()
    ///   .verbose_output(true)
    ///   .sources_to_targets([utrecht],[amsterdam,rotterdam,den_haag])
    ///   .date_time(DateTime::from_departure_time(chrono::Local::now().naive_local()))
    ///   .costing(Costing::Auto(Default::default()));
    ///
    /// let response = Valhalla::default()
    ///   .matrix(manifest).await
    ///   .unwrap();
    /// # use valhalla_client::matrix::Response;
    /// # if let Response::Verbose(r) = response{
    /// #   assert!(r.warnings.is_empty());
    /// #   assert_eq!(r.sources.len(),1);
    /// #   assert_eq!(r.targets.len(),3);
    /// # };
    /// # }
    /// ```
    pub async fn matrix(&self, manifest: matrix::Manifest) -> Result<matrix::Response, Error> {
        debug_assert_ne!(
            manifest.targets.len(),
            0,
            "a matrix route needs at least one target specified"
        );
        debug_assert_ne!(
            manifest.sources.len(),
            0,
            "a matrix route needs at least one source specified"
        );

        self.do_request(manifest, "sources_to_targets", "matrix")
            .await
    }
    /// Make an elevation request
    ///
    /// Valhalla's elevation lookup service provides digital elevation model (DEM) data as the result of a query.
    /// The elevation service data has many applications when combined with other routing and navigation data, including computing the steepness of roads and paths or generating an elevation profile chart along a route.
    ///
    /// For example, you can get elevation data for a point, a trail, or a trip.
    /// You might use the results to consider hills for your bicycle trip, or when estimating battery usage for trips in electric vehicles.
    ///
    /// See <https://valhalla.github.io/valhalla/api/elevation/api-reference/> for details
    ///
    /// # Example:
    ///
    /// ```rust,no_run
    /// # async fn elevation() {
    /// use valhalla_client::Valhalla;
    /// use valhalla_client::elevation::Manifest;
    ///
    /// let request = Manifest::builder()
    ///   .shape([
    ///     (40.712431, -76.504916),
    ///     (40.712275, -76.605259),
    ///     (40.712122, -76.805694),
    ///     (40.722431, -76.884916),
    ///     (40.812275, -76.905259),
    ///     (40.912122, -76.965694),
    ///   ])
    ///   .include_range();
    /// let response = Valhalla::default()
    ///   .elevation(request).await.unwrap();
    /// # assert!(response.height.is_empty());
    /// # assert_eq!(response.range_height.len(), 6);
    /// # assert!(response.encoded_polyline.is_none());
    /// # assert!(response.warnings.is_empty());
    /// # assert_eq!(response.x_coordinate, None);
    /// # assert_eq!(response.y_coordinate, None);
    /// # assert_eq!(response.shape.map(|s|s.len()),Some(6));
    /// # }
    /// ```
    pub async fn elevation(
        &self,
        manifest: elevation::Manifest,
    ) -> Result<elevation::Response, Error> {
        self.do_request(manifest, "height", "elevation").await
    }
    /// Make a status request
    ///
    /// This can be used as a health endpoint for the HTTP API or to toggle features in a frontend.
    ///
    /// See <https://valhalla.github.io/valhalla/api/status/api-reference/> for details
    ///
    /// # Example:
    /// ```rust,no_run
    /// # async fn status(){
    /// use valhalla_client::Valhalla;
    /// use valhalla_client::status::Manifest;
    ///
    /// let request = Manifest::builder()
    ///   .verbose_output(false);
    /// let response = Valhalla::default()
    ///   .status(request).await.unwrap();
    /// # assert!(response.version >= semver::Version::parse("3.1.4").unwrap());
    /// # assert!(response.tileset_last_modified.timestamp() > 0);
    /// # assert!(response.verbose.is_none());
    /// # }
    /// ```
    pub async fn status(&self, manifest: status::Manifest) -> Result<status::Response, Error> {
        self.do_request(manifest, "status", "status").await
    }

    /// Make a trace_attributes request for map matching with edge attributes
    ///
    /// See <https://valhalla.github.io/valhalla/api/map-matching/api-reference/> for details
    ///
    /// # Example:
    /// ```rust
    /// # async fn trace_attributes() {
    /// use valhalla_client::Valhalla;
    /// use valhalla_client::trace_attributes::{Manifest, TracePoint};
    /// use valhalla_client::costing::Costing;
    ///
    /// let manifest = Manifest::builder(
    ///   [TracePoint::new(52.3676, 4.9041), TracePoint::new(52.0907, 5.1214)],
    ///   Costing::Auto(Default::default()),
    /// )
    /// .include_attributes(["edge.surface", "edge.road_class", "edge.length"]);
    ///
    /// let response = Valhalla::default()
    ///   .trace_attributes(manifest).await.unwrap();
    /// # assert!(!response.edges.is_empty());
    /// # }
    /// ```
    pub async fn trace_attributes(
        &self,
        manifest: trace_attributes::Manifest,
    ) -> Result<trace_attributes::Response, Error> {
        self.do_request(manifest, "trace_attributes", "trace_attributes")
            .await
    }

    async fn do_request<Resp: for<'de> serde::Deserialize<'de>>(
        &self,
        manifest: impl serde::Serialize,
        path: &'static str,
        name: &'static str,
    ) -> Result<Resp, Error> {
        if log::log_enabled!(log::Level::Trace) {
            let request = serde_json::to_string(&manifest).map_err(Error::Serde)?;
            trace!("Sending {name} request: {request}");
        }
        let mut url = self.base_url.clone();
        url.path_segments_mut()
            .expect("base_url is not a valid base url")
            .push(path);
        let response = self
            .client
            .post(url)
            .json(&manifest)
            .send()
            .await
            .map_err(Error::Reqwest)?;
        if response.status().is_client_error() {
            return Err(Error::RemoteError(
                response.json().await.map_err(Error::Reqwest)?,
            ));
        }
        response.error_for_status_ref().map_err(Error::Reqwest)?;
        let text = response.text().await.map_err(Error::Reqwest)?;
        trace!("{name} responded: {text}");
        let response: Resp = serde_json::from_str(&text).map_err(Error::Serde)?;
        Ok(response)
    }
}

impl Default for Valhalla {
    fn default() -> Self {
        Self::new(
            url::Url::parse(VALHALLA_PUBLIC_API_URL)
                .expect("VALHALLA_PUBLIC_API_URL is not a valid url"),
        )
    }
}