everymap-core 0.2.1

Core traits, types, and error handling for EveryMap — unified geospatial API abstraction
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
use crate::error::EveryMapResult;
use crate::types::{BoundingBox, Coordinate, Polyline};
use async_trait::async_trait;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;

impl fmt::Display for DepartureTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DepartureTime::Now => f.write_str("now"),
            DepartureTime::Timestamp(ts) => write!(f, "{}", ts),
            DepartureTime::Iso8601(s) => f.write_str(s),
        }
    }
}

/// Typed departure time for routing, matching, and isoline requests.
///
/// Replaces fragile `Option<String>` guessing with an explicit enum.
/// Serializes as a plain string for backward compatibility.
#[derive(Debug, Clone, PartialEq)]
pub enum DepartureTime {
    /// Depart now.
    Now,
    /// Unix timestamp in seconds.
    Timestamp(i64),
    /// ISO 8601 formatted date/time string.
    Iso8601(String),
}

impl Serialize for DepartureTime {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let s = match self {
            DepartureTime::Now => "now".to_string(),
            DepartureTime::Timestamp(ts) => ts.to_string(),
            DepartureTime::Iso8601(s) => s.clone(),
        };
        serializer.serialize_str(&s)
    }
}

impl<'de> Deserialize<'de> for DepartureTime {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        if s == "now" {
            Ok(DepartureTime::Now)
        } else if let Ok(ts) = s.parse::<i64>() {
            Ok(DepartureTime::Timestamp(ts))
        } else {
            Ok(DepartureTime::Iso8601(s))
        }
    }
}

/// Avoid types for routing restrictions.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum AvoidType {
    Tolls,
    Ferries,
    Tunnels,
    Highways,
    DirtRoads,
}

/// Options for route calculation.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RouteOptions {
    /// Transport mode for the route
    pub transport_mode: Option<TransportMode>,
    /// Number of alternative routes to compute
    pub alternatives: Option<u32>,
    /// Route restrictions (tolls, ferries, highways, etc.)
    pub avoid: Vec<AvoidType>,
    /// Departure time
    pub departure_time: Option<DepartureTime>,
    /// Arrival time
    pub arrival_time: Option<DepartureTime>,
    /// Preferred response language (BCP 47 language tag)
    pub language: Option<String>,
    /// Provider-specific options (HERE: routing_mode, spans, truck params; Google: waypoints, traffic_model)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_extra: Option<serde_json::Value>,
}

/// Transport mode for a route.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum TransportMode {
    Car,
    Truck,
    Pedestrian,
    Bicycle,
    Scooter,
    Bus,
    Taxi,
    Unknown,
}

/// A single leg/step in a route (e.g., a turn-by-turn instruction).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteStep {
    /// Instruction text (e.g., "Turn right onto Main St")
    pub instruction: Option<String>,
    /// Distance of this step in meters
    pub distance: Option<f64>,
    /// Duration of this step in seconds
    pub duration: Option<f64>,
    /// Starting coordinate of this step
    pub start_coordinate: Option<Coordinate>,
    /// Ending coordinate of this step
    pub end_coordinate: Option<Coordinate>,
}

/// A unified route result from the core trait.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteResult {
    /// Total route distance in meters
    pub distance: f64,
    /// Total route duration in seconds
    pub duration: f64,
    /// Route geometry as a polyline
    pub geometry: Polyline,
    /// Transport mode used for this route
    pub transport_mode: Option<TransportMode>,
    /// Turn-by-turn steps (if available)
    pub steps: Vec<RouteStep>,
    /// Bounding box for the route (if available)
    pub bounding_box: Option<BoundingBox>,
    /// Provider-specific raw data for advanced use cases
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub raw: Option<serde_json::Value>,
}

/// A unified route response from the core trait.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteResponse {
    /// The route results (may contain alternatives)
    pub routes: Vec<RouteResult>,
}

#[async_trait]
pub trait Router: Send + Sync {
    async fn calculate_route(
        &self,
        start: &Coordinate,
        end: &Coordinate,
        options: &RouteOptions,
    ) -> EveryMapResult<RouteResponse>;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_route_options_default() {
        let options = RouteOptions::default();
        assert!(options.transport_mode.is_none());
        assert!(options.alternatives.is_none());
        assert!(options.avoid.is_empty());
        assert!(options.departure_time.is_none());
        assert!(options.arrival_time.is_none());
        assert!(options.language.is_none());
        assert!(options.provider_extra.is_none());
    }

    #[test]
    fn test_route_options_with_fields() {
        let options = RouteOptions {
            transport_mode: Some(TransportMode::Car),
            alternatives: Some(3),
            avoid: vec![AvoidType::Tolls, AvoidType::Ferries],
            language: Some("de-DE".to_string()),
            provider_extra: Some(serde_json::json!({"routing_mode": "fast"})),
            ..Default::default()
        };
        assert_eq!(options.transport_mode, Some(TransportMode::Car));
        assert_eq!(options.alternatives, Some(3));
        assert_eq!(options.avoid.len(), 2);
    }

    #[test]
    fn test_transport_mode_serialization() {
        assert_eq!(
            serde_json::to_string(&TransportMode::Car).unwrap(),
            "\"Car\""
        );
        let mode: TransportMode = serde_json::from_str("\"Truck\"").unwrap();
        assert_eq!(mode, TransportMode::Truck);
    }

    #[test]
    fn test_avoid_type_serialization() {
        assert_eq!(
            serde_json::to_string(&AvoidType::Tolls).unwrap(),
            "\"Tolls\""
        );
        let avoid: AvoidType = serde_json::from_str("\"Highways\"").unwrap();
        assert_eq!(avoid, AvoidType::Highways);
    }

    #[test]
    fn test_route_result_construction() {
        let result = RouteResult {
            distance: 15000.0,
            duration: 1800.0,
            geometry: Polyline::new(vec![]),
            transport_mode: Some(TransportMode::Car),
            steps: vec![],
            bounding_box: None,
            raw: None,
        };
        assert_eq!(result.distance, 15000.0);
        assert_eq!(result.duration, 1800.0);
        assert_eq!(result.transport_mode, Some(TransportMode::Car));
    }

    // --- AvoidType all 5 variants serde roundtrip ---

    #[test]
    fn test_avoid_type_all_variants_serde() {
        let variants = [
            AvoidType::Tolls,
            AvoidType::Ferries,
            AvoidType::Tunnels,
            AvoidType::Highways,
            AvoidType::DirtRoads,
        ];
        for v in &variants {
            let json = serde_json::to_string(v).unwrap();
            let back: AvoidType = serde_json::from_str(&json).unwrap();
            assert_eq!(*v, back, "Failed roundtrip for {:?}", v);
        }
    }

    #[test]
    fn test_avoid_type_all_variants_distinct() {
        let variants = [
            AvoidType::Tolls,
            AvoidType::Ferries,
            AvoidType::Tunnels,
            AvoidType::Highways,
            AvoidType::DirtRoads,
        ];
        for i in 0..variants.len() {
            for j in 0..variants.len() {
                if i != j {
                    assert_ne!(variants[i], variants[j]);
                }
            }
        }
    }

    // --- TransportMode all 8 variants serde roundtrip ---

    #[test]
    fn test_transport_mode_all_variants_serde() {
        let variants = [
            TransportMode::Car,
            TransportMode::Truck,
            TransportMode::Pedestrian,
            TransportMode::Bicycle,
            TransportMode::Scooter,
            TransportMode::Bus,
            TransportMode::Taxi,
            TransportMode::Unknown,
        ];
        for v in &variants {
            let json = serde_json::to_string(v).unwrap();
            let back: TransportMode = serde_json::from_str(&json).unwrap();
            assert_eq!(*v, back, "Failed roundtrip for {:?}", v);
        }
    }

    #[test]
    fn test_transport_mode_all_variants_distinct() {
        let variants = [
            TransportMode::Car,
            TransportMode::Truck,
            TransportMode::Pedestrian,
            TransportMode::Bicycle,
            TransportMode::Scooter,
            TransportMode::Bus,
            TransportMode::Taxi,
            TransportMode::Unknown,
        ];
        for i in 0..variants.len() {
            for j in 0..variants.len() {
                if i != j {
                    assert_ne!(variants[i], variants[j]);
                }
            }
        }
    }

    // --- RouteResponse serde roundtrip ---

    #[test]
    fn test_route_response_serde_roundtrip() {
        let response = RouteResponse {
            routes: vec![RouteResult {
                distance: 15000.0,
                duration: 1800.0,
                geometry: Polyline::new(vec![]),
                transport_mode: Some(TransportMode::Car),
                steps: vec![],
                bounding_box: None,
                raw: None,
            }],
        };
        let json = serde_json::to_string(&response).unwrap();
        let back: RouteResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(back.routes.len(), 1);
        assert_eq!(back.routes[0].distance, 15000.0);
        assert_eq!(back.routes[0].transport_mode, Some(TransportMode::Car));
    }

    #[test]
    fn test_route_response_empty_routes() {
        let response = RouteResponse { routes: vec![] };
        let json = serde_json::to_string(&response).unwrap();
        let back: RouteResponse = serde_json::from_str(&json).unwrap();
        assert!(back.routes.is_empty());
    }

    // --- RouteOptions with provider_extra serde roundtrip ---

    #[test]
    fn test_route_options_serde_roundtrip() {
        let options = RouteOptions {
            transport_mode: Some(TransportMode::Truck),
            alternatives: Some(2),
            avoid: vec![AvoidType::Tolls, AvoidType::Ferries],
            departure_time: Some(DepartureTime::Iso8601("2024-06-01T08:00:00".to_string())),
            arrival_time: None,
            language: Some("en".to_string()),
            provider_extra: Some(
                serde_json::json!({"routing_mode": "fast", "truck": {"weight": 18}}),
            ),
        };
        let json = serde_json::to_string(&options).unwrap();
        let back: RouteOptions = serde_json::from_str(&json).unwrap();
        assert_eq!(back.transport_mode, Some(TransportMode::Truck));
        assert_eq!(back.alternatives, Some(2));
        assert_eq!(back.avoid.len(), 2);
        assert!(back.provider_extra.is_some());
    }

    // --- RouteStep serde roundtrip ---

    #[test]
    fn test_route_step_serde_roundtrip() {
        let step = RouteStep {
            instruction: Some("Turn right onto Main St".to_string()),
            distance: Some(500.0),
            duration: Some(60.0),
            start_coordinate: Some(Coordinate::new(52.5, 13.4).unwrap()),
            end_coordinate: Some(Coordinate::new(52.51, 13.41).unwrap()),
        };
        let json = serde_json::to_string(&step).unwrap();
        let back: RouteStep = serde_json::from_str(&json).unwrap();
        assert_eq!(back.instruction.as_deref(), Some("Turn right onto Main St"));
        assert_eq!(back.distance, Some(500.0));
        assert_eq!(back.duration, Some(60.0));
    }

    // --- RouteResult with all fields populated ---

    #[test]
    fn test_route_result_full_serde_roundtrip() {
        let result = RouteResult {
            distance: 0.0,
            duration: 0.0,
            geometry: Polyline::new(vec![Coordinate::new(52.5, 13.4).unwrap()]),
            transport_mode: Some(TransportMode::Pedestrian),
            steps: vec![RouteStep {
                instruction: Some("Walk north".to_string()),
                distance: Some(100.0),
                duration: Some(120.0),
                start_coordinate: None,
                end_coordinate: None,
            }],
            bounding_box: Some(BoundingBox::new(
                Coordinate::new(52.6, 13.5).unwrap(),
                Coordinate::new(52.4, 13.3).unwrap(),
            )),
            raw: Some(serde_json::json!({"legs": []})),
        };
        let json = serde_json::to_string(&result).unwrap();
        let back: RouteResult = serde_json::from_str(&json).unwrap();
        assert_eq!(back.distance, 0.0);
        assert_eq!(back.steps.len(), 1);
        assert!(back.bounding_box.is_some());
        assert!(back.raw.is_some());
    }

    // --- Edge cases ---

    #[test]
    fn test_route_result_zero_distance_duration() {
        let result = RouteResult {
            distance: 0.0,
            duration: 0.0,
            geometry: Polyline::new(vec![]),
            transport_mode: None,
            steps: vec![],
            bounding_box: None,
            raw: None,
        };
        assert_eq!(result.distance, 0.0);
        assert_eq!(result.duration, 0.0);
    }

    #[test]
    fn test_route_options_all_avoid_types() {
        let options = RouteOptions {
            avoid: vec![
                AvoidType::Tolls,
                AvoidType::Ferries,
                AvoidType::Tunnels,
                AvoidType::Highways,
                AvoidType::DirtRoads,
            ],
            ..Default::default()
        };
        assert_eq!(options.avoid.len(), 5);
    }

    // --- DepartureTime serde ---

    #[test]
    fn test_departure_time_now_serde() {
        let json = serde_json::to_string(&DepartureTime::Now).unwrap();
        assert_eq!(json, "\"now\"");
        let back: DepartureTime = serde_json::from_str(&json).unwrap();
        assert_eq!(back, DepartureTime::Now);
    }

    #[test]
    fn test_departure_time_timestamp_serde() {
        let dt = DepartureTime::Timestamp(1717200000);
        let json = serde_json::to_string(&dt).unwrap();
        assert_eq!(json, "\"1717200000\"");
        let back: DepartureTime = serde_json::from_str(&json).unwrap();
        assert_eq!(back, DepartureTime::Timestamp(1717200000));
    }

    #[test]
    fn test_departure_time_iso8601_serde() {
        let dt = DepartureTime::Iso8601("2024-06-01T08:00:00Z".to_string());
        let json = serde_json::to_string(&dt).unwrap();
        assert_eq!(json, "\"2024-06-01T08:00:00Z\"");
        let back: DepartureTime = serde_json::from_str(&json).unwrap();
        assert_eq!(
            back,
            DepartureTime::Iso8601("2024-06-01T08:00:00Z".to_string())
        );
    }
}