ferrostar 0.49.0

The core of modern turn-by-turn navigation.
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
//! Response parsing for OSRM-compatible JSON (including Stadia Maps, Valhalla, Mapbox, etc.).

pub(crate) mod models;
pub mod utilities;

use super::RouteResponseParser;
use crate::models::{
    AnyAnnotationValue, DrivingSide, GeographicCoordinate, Incident, LaneInfo, RouteStep,
    SpokenInstruction, VisualInstruction, VisualInstructionContent, Waypoint, WaypointKind,
};
use crate::routing_adapters::osrm::models::OsrmWaypointProperties;
use crate::routing_adapters::utilities::get_coordinates_from_geometry;
use crate::routing_adapters::{
    ParsingError, Route,
    osrm::models::{
        Route as OsrmRoute, RouteResponse, RouteStep as OsrmRouteStep, Waypoint as OsrmWaypoint,
    },
};
#[cfg(all(not(feature = "std"), feature = "alloc"))]
use alloc::{string::ToString, vec, vec::Vec};
use geo::BoundingRect;
use models::BannerContent;
use polyline::decode_polyline;
use utilities::get_annotation_slice;
use uuid::Uuid;

/// A response parser for OSRM-compatible routing backends.
///
/// The parser is NOT limited to only the standard OSRM format; many Valhalla/Mapbox tags are also
/// parsed and are included in the final route.
///
/// # Waypoint properties
///
/// Waypoint properties will always be returned as UTF-8 encoded JSON bytes.
/// This adapter knows about properties defined in [`OsrmWaypointProperties`].
/// However, some servers (like the Valhalla derivatives run by Stadia Maps and Mapbox)
/// **may not echo back all rich location properties in OSRM mode**.
/// Keep this in mind when designing your rerouting flow.
#[derive(Debug)]
pub struct OsrmResponseParser {
    polyline_precision: u32,
}

impl OsrmResponseParser {
    pub fn new(polyline_precision: u32) -> Self {
        Self { polyline_precision }
    }
}

impl RouteResponseParser for OsrmResponseParser {
    fn parse_response(&self, response: Vec<u8>) -> Result<Vec<Route>, ParsingError> {
        let res: RouteResponse = serde_json::from_slice(&response)?;

        if res.code == "Ok" {
            res.routes
                .iter()
                .map(|route| Route::from_osrm(route, &res.waypoints, self.polyline_precision))
                .collect::<Result<Vec<_>, _>>()
        } else {
            Err(ParsingError::InvalidStatusCode {
                code: res.code,
                description: res.message,
            })
        }
    }
}

impl Route {
    /// Create a route from an OSRM route and OSRM waypoints.
    ///
    /// # Arguments
    /// * `route` - The OSRM route.
    /// * `waypoints` - The OSRM waypoints. Properties, if present, are a JSON serialized [`OsrmWaypointProperties`] object.
    /// * `polyline_precision` - The precision of the polyline.
    pub fn from_osrm(
        route: &OsrmRoute,
        waypoints: &[OsrmWaypoint],
        polyline_precision: u32,
    ) -> Result<Self, ParsingError> {
        let via_waypoint_indices: Vec<_> = route
            .legs
            .iter()
            .flat_map(|leg| leg.via_waypoints.iter().map(|via| via.waypoint_index))
            .collect();

        let waypoints: Vec<_> = waypoints
            .iter()
            .enumerate()
            .map(|(idx, waypoint)| Waypoint {
                coordinate: GeographicCoordinate {
                    lat: waypoint.location.latitude(),
                    lng: waypoint.location.longitude(),
                },
                kind: if via_waypoint_indices.contains(&idx) {
                    WaypointKind::Via
                } else {
                    WaypointKind::Break
                },
                properties: if waypoint.name.is_some() || waypoint.distance.is_some() {
                    Some(
                        #[expect(clippy::missing_panics_doc)]
                        serde_json::to_vec(&OsrmWaypointProperties {
                            name: waypoint.name.clone(),
                            distance: waypoint.distance,
                        })
                        .expect("Infallible JSON serialization"),
                    )
                } else {
                    None
                },
            })
            .collect();

        Self::from_osrm_with_standard_waypoints(route, &waypoints, polyline_precision)
    }

    /// Create a route from an OSRM route and Ferrostar waypoints.
    ///
    /// # Arguments
    /// * `route` - The OSRM route.
    /// * `waypoints` - The Ferrostar waypoints.
    /// * `polyline_precision` - The precision of the polyline.
    pub fn from_osrm_with_standard_waypoints(
        route: &OsrmRoute,
        waypoints: &[Waypoint],
        polyline_precision: u32,
    ) -> Result<Self, ParsingError> {
        let linestring = decode_polyline(&route.geometry, polyline_precision).map_err(|error| {
            ParsingError::InvalidGeometry {
                error: error.to_string(),
            }
        })?;
        if let Some(bbox) = linestring.bounding_rect() {
            let geometry: Vec<GeographicCoordinate> = linestring
                .coords()
                .map(|coord| GeographicCoordinate::from(*coord))
                .collect();

            let steps = route
                .legs
                .iter()
                .flat_map(|leg| {
                    // Converts all single value annotation vectors into a single vector with a value object.
                    let annotations = leg
                        .annotation
                        .as_ref()
                        .map(|leg_annotation| utilities::zip_annotations(leg_annotation.clone()));

                    // Convert all incidents into a vector of Incident objects.
                    let incident_items = leg
                        .incidents
                        .iter()
                        .map(Incident::from)
                        .collect::<Vec<Incident>>();

                    // Index for the annotations slice
                    let mut start_index: usize = 0;

                    leg.steps.iter().map(move |step| {
                        let step_geometry =
                            get_coordinates_from_geometry(&step.geometry, polyline_precision)?;

                        // Slice the annotations for the current step.
                        // The annotations array represents segments between coordinates.
                        //
                        // 1. Annotations should never repeat.
                        // 2. Each step has one less annotation than coordinate.
                        // 3. The last step never has annotations as it's two of the route's last coordinate (duplicate).
                        let step_index_len = step_geometry.len() - 1_usize;
                        let end_index = start_index + step_index_len;

                        let annotation_slice =
                            get_annotation_slice(annotations.clone(), start_index, end_index).ok();

                        let relevant_incidents_slice = incident_items
                            .iter()
                            .filter(|incident| {
                                let incident_start = incident.geometry_index_start as usize;

                                match incident.geometry_index_end {
                                    Some(end) => {
                                        let incident_end = end as usize;
                                        incident_start >= start_index && incident_end <= end_index
                                    }
                                    None => {
                                        incident_start >= start_index && incident_start <= end_index
                                    }
                                }
                            })
                            .map(|incident| {
                                let mut adjusted_incident = incident.clone();
                                if adjusted_incident.geometry_index_start - start_index as u64 > 0 {
                                    adjusted_incident.geometry_index_start -= start_index as u64;
                                } else {
                                    adjusted_incident.geometry_index_start = 0;
                                }

                                if let Some(end) = adjusted_incident.geometry_index_end {
                                    let adjusted_end = end - start_index as u64;
                                    adjusted_incident.geometry_index_end =
                                        Some(if adjusted_end > end_index as u64 {
                                            end_index as u64
                                        } else {
                                            adjusted_end
                                        });
                                }
                                adjusted_incident
                            })
                            .collect::<Vec<Incident>>();

                        start_index = end_index;

                        Ok(RouteStep::from_osrm_and_geom(
                            step,
                            step_geometry,
                            annotation_slice,
                            relevant_incidents_slice,
                        ))
                    })
                })
                .collect::<Result<Vec<_>, ParsingError>>()?;

            Ok(Route {
                geometry,
                bbox: bbox.into(),
                distance: route.distance,
                waypoints: waypoints.into(),
                steps,
            })
        } else {
            Err(ParsingError::InvalidGeometry {
                error: "Bounding box could not be calculated".to_string(),
            })
        }
    }
}

impl RouteStep {
    fn extract_exit_numbers(banner_content: &BannerContent) -> Vec<String> {
        banner_content
            .components
            .iter()
            .filter(|component| component.component_type.as_deref() == Some("exit-number"))
            .filter_map(|component| component.text.clone())
            .collect()
    }

    fn from_osrm_and_geom(
        value: &OsrmRouteStep,
        geometry: Vec<GeographicCoordinate>,
        annotations: Option<Vec<AnyAnnotationValue>>,
        incidents: Vec<Incident>,
    ) -> Self {
        let visual_instructions = value
            .banner_instructions
            .iter()
            .map(|banner| VisualInstruction {
                primary_content: VisualInstructionContent {
                    text: banner.primary.text.clone(),
                    maneuver_type: banner.primary.maneuver_type,
                    maneuver_modifier: banner.primary.maneuver_modifier,
                    roundabout_exit_degrees: banner.primary.roundabout_exit_degrees,
                    lane_info: None,
                    exit_numbers: Self::extract_exit_numbers(&banner.primary),
                },
                secondary_content: banner.secondary.as_ref().map(|secondary| {
                    VisualInstructionContent {
                        text: secondary.text.clone(),
                        maneuver_type: secondary.maneuver_type,
                        maneuver_modifier: secondary.maneuver_modifier,
                        roundabout_exit_degrees: banner.primary.roundabout_exit_degrees,
                        lane_info: None,
                        exit_numbers: Self::extract_exit_numbers(secondary),
                    }
                }),
                sub_content: banner.sub.as_ref().map(|sub| VisualInstructionContent {
                    text: sub.text.clone(),
                    maneuver_type: sub.maneuver_type,
                    maneuver_modifier: sub.maneuver_modifier,
                    roundabout_exit_degrees: sub.roundabout_exit_degrees,
                    lane_info: {
                        let lane_infos: Vec<LaneInfo> = sub
                            .components
                            .iter()
                            .filter(|component| component.component_type.as_deref() == Some("lane"))
                            .map(|component| LaneInfo {
                                active: component.active.unwrap_or(false),
                                directions: component.directions.clone().unwrap_or_default(),
                                active_direction: component.active_direction.clone(),
                            })
                            .collect();

                        if lane_infos.is_empty() {
                            None
                        } else {
                            Some(lane_infos)
                        }
                    },
                    exit_numbers: Self::extract_exit_numbers(sub),
                }),
                trigger_distance_before_maneuver: banner.distance_along_geometry,
            })
            .collect();

        let spoken_instructions = value
            .voice_instructions
            .iter()
            .map(|instruction| SpokenInstruction {
                text: instruction.announcement.clone(),
                ssml: instruction.ssml_announcement.clone(),
                trigger_distance_before_maneuver: instruction.distance_along_geometry,
                utterance_id: Uuid::new_v4(),
            })
            .collect();

        // Convert the annotations to a vector of json strings.
        // This allows us to safely pass the RouteStep through the FFI boundary.
        // The host platform can then parse an arbitrary annotation object.
        let annotations_as_strings: Option<Vec<String>> = annotations.map(|annotations_vec| {
            annotations_vec
                .iter()
                .map(|annotation| serde_json::to_string(annotation).unwrap())
                .collect()
        });

        let exits = match value.exits.clone() {
            Some(exit_text) => exit_text.split(';').map(|s| s.trim().to_string()).collect(),
            None => Vec::new(),
        };

        let driving_side = value.driving_side.as_deref().and_then(|s| match s {
            "left" => Some(DrivingSide::Left),
            "right" => Some(DrivingSide::Right),
            _ => None,
        });

        RouteStep {
            geometry,
            // TODO: Investigate using the haversine distance or geodesics to normalize.
            // Valhalla in particular is a bit nonstandard. See https://github.com/valhalla/valhalla/issues/1717
            distance: value.distance,
            duration: value.duration,
            road_name: value.name.clone(),
            exits,
            instruction: value.maneuver.get_instruction(),
            visual_instructions,
            spoken_instructions,
            annotations: annotations_as_strings,
            incidents,
            driving_side,
            roundabout_exit_number: value.maneuver.exit,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::{TestRoute, redact_properties};

    #[test]
    fn parse_standard_osrm() {
        let routes = TestRoute::StandardOsrm.parse();
        insta::assert_yaml_snapshot!(routes, {
            "[].waypoints[].properties" => insta::dynamic_redaction(redact_properties::<OsrmWaypointProperties>),
        });
    }

    #[test]
    fn parse_valhalla_osrm() {
        let routes = TestRoute::Valhalla.parse();

        insta::assert_yaml_snapshot!(routes, {
            ".**.annotations" => "redacted annotations json strings vec",
            "[].waypoints[].properties" => insta::dynamic_redaction(redact_properties::<OsrmWaypointProperties>),
        });
    }

    #[test]
    fn parse_valhalla_osrm_with_via_ways() {
        let routes = TestRoute::ValhallaViaWays.parse();

        insta::assert_yaml_snapshot!(routes, {
            ".**.annotations" => "redacted annotations json strings vec",
            "[].waypoints[].properties" => insta::dynamic_redaction(redact_properties::<OsrmWaypointProperties>),
        });
    }

    #[test]
    fn parse_valhalla_asserting_annotation_lengths() {
        let routes = TestRoute::Valhalla.parse();

        // Loop through every step and validate that the length of the annotations
        // matches the length of the geometry minus one. This is because each annotation
        // represents a segment between two coordinates.
        for (route_index, route) in routes.iter().enumerate() {
            for (step_index, step) in route.steps.iter().enumerate() {
                if step_index == route.steps.len() - 1 {
                    // The arrival step is 2 of the same coordinates.
                    // So annotations will be None.
                    assert_eq!(step.annotations, None);
                    continue;
                }

                let step = step.clone();
                let annotations = step.annotations.expect("No annotations");
                assert_eq!(
                    annotations.len(),
                    step.geometry.len() - 1,
                    "Route {}, Step {}",
                    route_index,
                    step_index
                );
            }
        }
    }

    #[test]
    fn parse_valhalla_asserting_sub_maneuvers() {
        let routes = TestRoute::ValhallaExtended.parse();

        // Collect all sub_contents into a vector
        let sub_contents: Vec<_> = routes
            .iter()
            .flat_map(|route| &route.steps)
            .filter_map(|step| {
                step.visual_instructions
                    .iter()
                    .find_map(|instruction: &VisualInstruction| instruction.sub_content.as_ref())
            })
            .collect();

        // Assert that there's exactly one sub maneuver instructions as is the case in the test data
        assert_eq!(
            sub_contents.len(),
            1,
            "Expected exactly one sub banner instructions"
        );

        if let Some(sub_content) = sub_contents.first() {
            // Ensure that there are 4 pieces of lane information in the sub banner instructions
            if let Some(lane_info) = &sub_content.lane_info {
                assert_eq!(lane_info.len(), 4);
            } else {
                panic!("Expected lane information, but could not find it");
            }
        } else {
            panic!("No sub banner instructions found in any of the steps")
        }
    }

    #[test]
    fn parse_osrm_with_exits() {
        let routes = TestRoute::ValhallaWithExits.parse();

        insta::assert_yaml_snapshot!(routes, {
            ".**.annotations" => "redacted annotations json strings vec",
            "[].waypoints[].properties" => insta::dynamic_redaction(redact_properties::<OsrmWaypointProperties>),
        });
    }

    #[test]
    fn parse_valhalla_osrm_with_roundabouts() {
        let routes = TestRoute::ValhallaWithRoundabouts.parse();

        insta::assert_yaml_snapshot!(routes, {
            ".**.annotations" => "redacted annotations json strings vec",
            "[].waypoints[].properties" => insta::dynamic_redaction(redact_properties::<OsrmWaypointProperties>),
        });
    }

    #[test]
    fn parse_valhalla_roundabout_fields() {
        let routes = TestRoute::ValhallaWithRoundabouts.parse();

        let route = &routes[0];

        // Collect steps that have roundabout exit numbers
        let roundabout_steps: Vec<_> = route
            .steps
            .iter()
            .filter(|step| step.roundabout_exit_number.is_some())
            .collect();

        assert!(
            !roundabout_steps.is_empty(),
            "Expected at least one step with a roundabout exit number"
        );

        for step in &roundabout_steps {
            // Every step with a roundabout exit should also have a driving side
            assert!(
                step.driving_side.is_some(),
                "Roundabout step should have driving_side set"
            );
        }

        // All steps in this UK route should be left-hand driving
        for step in &route.steps {
            if let Some(driving_side) = step.driving_side {
                assert_eq!(
                    driving_side,
                    DrivingSide::Left,
                    "Expected left-hand driving for UK route"
                );
            }
        }
    }

    #[test]
    fn test_osrm_parser_with_empty_route_array() {
        let error_json = r#"{
            "code": "NoRoute",
            "message": "No route found between the given coordinates",
            "routes": []
        }"#;

        let parser = OsrmResponseParser::new(6);
        let result = parser.parse_response(error_json.as_bytes().to_vec());

        assert!(result.is_err());
        if let Err(ParsingError::InvalidStatusCode { code, description }) = result {
            assert_eq!(code, "NoRoute");
            assert_eq!(
                description,
                Some("No route found between the given coordinates".to_string())
            );
        } else {
            panic!("Expected InvalidStatusCode error with proper message");
        }
    }

    #[test]
    fn test_osrm_parser_with_missing_route_field() {
        let error_json = r#"{
            "code": "NoRoute",
            "message": "No route found between the given coordinates"
        }"#;

        let parser = OsrmResponseParser::new(6);
        let result = parser.parse_response(error_json.as_bytes().to_vec());

        assert!(result.is_err());
        if let Err(ParsingError::InvalidStatusCode { code, description }) = result {
            assert_eq!(code, "NoRoute");
            assert_eq!(
                description,
                Some("No route found between the given coordinates".to_string())
            );
        } else {
            panic!("Expected InvalidStatusCode error with proper message");
        }
    }
}