fastsim-schema 0.1.1

Vehicle database schema for the fastsim-vehicles repository
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
//! Database organizational schema version 1 for the `fastsim-vehicles` repository.
//!
//! Provides parsing, validation, and serialization of vehicle identification paths
//! (e.g., `v1/fastsim-3/conv/ford/fusion/2012/base/r1`) along with error handling
//! and index entry structures for vehicle discovery.

use super::*;

mod error;
mod index;
mod search;

#[cfg(feature = "wasm")]
mod wasm;

pub use error::VehicleSchemaV1Error;
pub use index::{read_jsonl_v1, write_jsonl_v1, IndexEntryV1};
pub use search::{search_v1, QueryV1};

/// Database organizational schema version 1 for the `fastsim-vehicles` repository.
///
/// Serializes to/from an 8-segment path-segment string, e.g. `"v1/fastsim-3/conv/ford/fusion/2012/base/r1"`
///
/// Segments in order:
/// 1. `v1` — schema version marker
/// 2. `fastsim-{N}` — FASTSim version
/// 3. `{powertrain}` — powertrain type (e.g., "conv", "hev", "phev", "bev")
/// 4. `{make}` — vehicle make
/// 5. `{model}` — vehicle model (may include trim information)
/// 6. `{year}` — model year or year range
/// 7. `{variant}` — variant/feature configuration (e.g., "base")
/// 8. `r{N}` — model revision/version for corrections
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(into = "String", try_from = "String")]
pub struct VehicleSchemaV1 {
    /// FASTSim version
    pub fastsim_version: u32,
    /// Powertrain type (e.g., "conv", "hev", "phev", "bev")
    pub powertrain: String,
    /// Vehicle make
    pub make: String,
    /// Vehicle model (may include trim information)
    pub model: String,
    /// Vehicle model year (or range of years)
    pub year: String,
    /// Vehicle variant (describes what modeling features are active, etc.)
    pub variant: String,
    /// Model revision/version for correcting model-level issues over time
    pub revision: u32,
}

impl std::fmt::Display for VehicleSchemaV1 {
    /// Display the schema as its path-segment string representation.
    ///
    /// Formats as: `v1/fastsim-{N}/{powertrain}/{make}/{model}/{year}/{variant}/r{N}`
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.path_segments().join("/"))
    }
}

impl From<VehicleSchemaV1> for String {
    fn from(s: VehicleSchemaV1) -> Self {
        s.to_string()
    }
}

impl std::str::FromStr for VehicleSchemaV1 {
    type Err = VehicleSchemaV1Error;
    /// Parse a schema from its path-segment string representation.
    ///
    /// Expected format (8 segments):
    /// `v1/fastsim-{N}/{powertrain}/{make}/{model}/{year}/{variant}/r{N}`
    ///
    /// # Errors
    /// This parser has two validation phases and may fail in either phase:
    /// - Structural parsing (`parse_structural`): wrong segment count, wrong required
    ///   prefixes, or non-numeric version fields.
    /// - Canonical identifier validation (`new`): any of `powertrain`, `make`, `model`,
    ///   `year`, or `variant` is not already a canonical identifier.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let raw = Self::parse_structural(s)?;
        Self::new(
            raw.fastsim_version,
            raw.powertrain,
            raw.make,
            raw.model,
            raw.year,
            raw.variant,
            raw.revision,
        )
    }
}

impl TryFrom<String> for VehicleSchemaV1 {
    type Error = VehicleSchemaV1Error;
    fn try_from(s: String) -> Result<Self, Self::Error> {
        s.parse()
    }
}

impl VehicleSchemaV1 {
    /// Parse a v1 schema path structurally, without canonical identifier validation.
    ///
    /// This only validates path shape and numeric fields:
    /// - 8 segments
    /// - `v1` schema prefix
    /// - `fastsim-{N}` and `r{N}` numeric segments
    ///
    /// It intentionally does not enforce canonical formatting for `powertrain`,
    /// `make`, `model`, `year`, or `variant`. Call `new` (or `from_str`) for full
    /// canonical validation.
    pub(crate) fn parse_structural(s: &str) -> Result<Self, VehicleSchemaV1Error> {
        let parts: Vec<&str> = s.split('/').collect();
        if parts.len() != 8 {
            return Err(VehicleSchemaV1Error::SegmentCount {
                input: s.to_string(),
                actual: parts.len(),
            });
        }
        if parts[0] != "v1" {
            return Err(VehicleSchemaV1Error::WrongSchemaPrefix {
                found: parts[0].to_string(),
            });
        }
        let fastsim_version = parts[1]
            .strip_prefix("fastsim-")
            .ok_or_else(|| VehicleSchemaV1Error::MissingFastsimVersionPrefix {
                segment: parts[1].to_string(),
            })?
            .parse::<u32>()
            .map_err(|source| VehicleSchemaV1Error::InvalidFastsimVersion {
                segment: parts[1].to_string(),
                source,
            })?;
        let revision = parts[7]
            .strip_prefix('r')
            .ok_or_else(|| VehicleSchemaV1Error::MissingRevisionPrefix {
                segment: parts[7].to_string(),
            })?
            .parse::<u32>()
            .map_err(|source| VehicleSchemaV1Error::InvalidRevision {
                segment: parts[7].to_string(),
                source,
            })?;

        Ok(Self {
            fastsim_version,
            powertrain: parts[2].to_string(),
            make: parts[3].to_string(),
            model: parts[4].to_string(),
            year: parts[5].to_string(),
            variant: parts[6].to_string(),
            revision,
        })
    }

    /// Construct a schema from parsed field values, enforcing canonical identifiers.
    ///
    /// # Errors
    /// Returns an error if any of `powertrain`, `make`, `model`, `year`, or `variant`
    /// is not already in canonical identifier form (lowercase, ASCII, dashes and periods allowed).
    pub fn new(
        fastsim_version: u32,
        powertrain: String,
        make: String,
        model: String,
        year: String,
        variant: String,
        revision: u32,
    ) -> Result<Self, VehicleSchemaV1Error> {
        for (field, segment) in [
            ("powertrain", &powertrain),
            ("make", &make),
            ("model", &model),
            ("year", &year),
            ("variant", &variant),
        ] {
            if !Self::validate_identifier(segment) {
                return Err(VehicleSchemaV1Error::InvalidIdentifier {
                    field,
                    value: segment.to_string(),
                    suggestion: Self::normalize_identifier(segment),
                });
            }
        }
        Ok(Self {
            fastsim_version,
            powertrain,
            make,
            model,
            year,
            variant,
            revision,
        })
    }

    /// Returns `false` if `c` is not in:
    /// - `a-z`
    /// - `0-9`
    /// - `-`
    /// - `.`
    fn allowed_character(c: char) -> bool {
        c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '.'
    }

    /// Convert arbitrary text into the canonical identifier format used by schema paths.
    /// Examples:
    /// - `"Outback XT"` → `"outback-xt"`
    /// - `"Model_3"` → `"model-3"`.
    pub fn normalize_identifier(s: &str) -> String {
        let mut result = String::new();
        let mut previous_was_dash = false;
        let mut previous_was_dot = false;

        for c in s.to_ascii_lowercase().chars() {
            let c = match c {
                c if Self::allowed_character(c) => c,
                _ => '-',
            };

            // Collapse repeated separators of the same type
            if c == '-' {
                if previous_was_dash {
                    continue;
                }
                previous_was_dash = true;
                previous_was_dot = false;
            } else if c == '.' {
                if previous_was_dot {
                    continue;
                }
                previous_was_dot = true;
                previous_was_dash = false;
            } else {
                previous_was_dash = false;
                previous_was_dot = false;
            }
            result.push(c);
        }

        result.trim_matches(|c| c == '-' || c == '.').to_string()
    }

    /// Validate that a string is a valid identifier for path segments.
    pub fn validate_identifier(s: &str) -> bool {
        !s.is_empty() && Self::normalize_identifier(s) == s
    }

    /// Suggests a normalized path when `raw` is structurally valid but not canonical.
    ///
    /// Returns `(current, suggested)` when a suggestion differs from the current path.
    pub fn suggest_normalized_path(raw: &str) -> Option<(String, String)> {
        let current = Self::parse_structural(raw).ok()?;

        let suggested = Self {
            fastsim_version: current.fastsim_version,
            powertrain: Self::normalize_identifier(&current.powertrain),
            make: Self::normalize_identifier(&current.make),
            model: Self::normalize_identifier(&current.model),
            year: Self::normalize_identifier(&current.year),
            variant: Self::normalize_identifier(&current.variant),
            revision: current.revision,
        };

        let current_path = current.to_string();
        let suggested_path = suggested.to_string();
        if current_path != suggested_path {
            Some((current_path, suggested_path))
        } else {
            None
        }
    }

    /// Build the ordered path segments as an 8-element array (without file extension).
    ///
    /// Returns in order:
    /// 1. "v1" — schema version marker
    /// 2. "fastsim-{N}" — FASTSim version
    /// 3. powertrain — e.g., "conv", "hev", "phev", "bev"
    /// 4. make — e.g., "ford", "tesla"
    /// 5. model — e.g., "fusion", "model-3"
    /// 6. year — e.g., "2012", "2020"
    /// 7. variant — e.g., "base", "trim-package"
    /// 8. "r{N}" — revision/version number
    pub fn path_segments(&self) -> [String; 8] {
        [
            "v1".to_string(),
            format!("fastsim-{}", self.fastsim_version),
            self.powertrain.clone(),
            self.make.clone(),
            self.model.clone(),
            self.year.clone(),
            self.variant.clone(),
            format!("r{}", self.revision),
        ]
    }

    /// Build a local file path by joining the schema's path-segment string with a base directory and extension.
    ///
    /// Example: `base_dir/v1/fastsim-3/conv/ford/fusion/2012/base/r1.yaml`
    pub fn build_filepath<P: AsRef<std::path::Path>>(
        &self,
        base_dir: P,
        extension: &str,
    ) -> std::path::PathBuf {
        base_dir.as_ref().join(format!("{}.{}", self, extension))
    }

    /// Build a remote URL by joining the schema's path-segment string with a base URL and extension.
    ///
    /// If `base_url` is None, uses the default GitHub raw content URL.
    /// Example: `https://raw.githubusercontent.com/.../v1/fastsim-3/conv/ford/fusion/2012/base/r1.yaml`
    pub fn build_url(&self, base_url: Option<&str>, extension: &str) -> String {
        format!(
            "{}/{}.{}",
            base_url
                .map(|s| s.trim_end_matches('/'))
                .unwrap_or(DEFAULT_DB_URL),
            self,
            extension
        )
    }
}

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

    fn sample_schema() -> VehicleSchemaV1 {
        VehicleSchemaV1::new(
            3,
            "conv".to_string(),
            "ford".to_string(),
            "fusion".to_string(),
            "2012".to_string(),
            "base".to_string(),
            1,
        )
        .unwrap()
    }

    #[test]
    fn test_serde_round_trip() {
        let schema = sample_schema();
        let serialized = serde_json::to_string(&schema).unwrap();
        assert_eq!(serialized, "\"v1/fastsim-3/conv/ford/fusion/2012/base/r1\"");
        let deserialized: VehicleSchemaV1 = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized, schema);
    }

    #[test]
    fn test_to_string() {
        let schema = sample_schema();
        assert_eq!(
            String::from(schema),
            "v1/fastsim-3/conv/ford/fusion/2012/base/r1"
        );
    }

    #[test]
    fn test_from_str() {
        let s = "v1/fastsim-3/conv/ford/fusion/2012/base/r1";
        let schema = VehicleSchemaV1::from_str(s).unwrap();
        assert_eq!(schema, sample_schema());
    }

    #[test]
    fn test_from_str_errors() {
        assert!(VehicleSchemaV1::from_str("v2/fastsim-3/conv/ford/fusion/2012/base/r1").is_err());
        assert!(VehicleSchemaV1::from_str("v1/fastsim-3/conv/ford/fusion/2012/base").is_err());
        assert!(VehicleSchemaV1::from_str("v1/bad-3/conv/ford/fusion/2012/base/r1").is_err());
        assert!(VehicleSchemaV1::from_str("v1/fastsim-3/conv/ford/fusion/2012/base/v1").is_err());
    }

    #[test]
    fn test_new_rejects_slash_in_fields() {
        assert!(VehicleSchemaV1::new(
            3,
            "conv".to_string(),
            "ford".to_string(),
            "f-150/raptor".to_string(),
            "2012".to_string(),
            "base".to_string(),
            1,
        )
        .is_err());
        assert!(VehicleSchemaV1::new(
            3,
            "conv".to_string(),
            "ford".to_string(),
            "fusion".to_string(),
            "2012".to_string(),
            "base/trim".to_string(),
            1,
        )
        .is_err());
    }

    #[test]
    fn test_new_allows_expected_characters() {
        assert!(VehicleSchemaV1::new(
            3,
            "conv".to_string(),
            "a-b-c-d-e-f0".to_string(),
            "model-3-long-range".to_string(),
            "2020".to_string(),
            "base-v1-2".to_string(),
            1,
        )
        .is_ok());
    }

    #[test]
    fn test_new_rejects_disallowed_characters() {
        assert!(VehicleSchemaV1::new(
            3,
            "conv".to_string(),
            "ford".to_string(),
            "fusion:se".to_string(),
            "2012".to_string(),
            "base".to_string(),
            1,
        )
        .is_err());
    }

    #[test]
    fn test_normalize_identifier_simple_cases() {
        assert_eq!(
            VehicleSchemaV1::normalize_identifier("Outback XT"),
            "outback-xt"
        );
        assert_eq!(
            VehicleSchemaV1::normalize_identifier("Model__3   Performance"),
            "model-3-performance"
        );
        assert_eq!(
            VehicleSchemaV1::normalize_identifier("f-150/raptor"),
            "f-150-raptor"
        );
        assert_eq!(VehicleSchemaV1::normalize_identifier("foo@bar"), "foo-bar");
        assert_eq!(VehicleSchemaV1::normalize_identifier("foo..bar"), "foo.bar");
        assert_eq!(
            VehicleSchemaV1::normalize_identifier("foo.-..bar"),
            "foo.-.bar"
        );
        assert_eq!(VehicleSchemaV1::normalize_identifier("foo/bar"), "foo-bar");
        assert_eq!(VehicleSchemaV1::normalize_identifier("---"), "");
    }

    #[test]
    fn test_normalize_engine_displacement() {
        assert_eq!(
            VehicleSchemaV1::normalize_identifier("Golf 1.5 TSI"),
            "golf-1.5-tsi"
        );
        assert_eq!(
            VehicleSchemaV1::normalize_identifier("F-150 3.5 EcoBoost"),
            "f-150-3.5-ecoboost"
        );
    }

    #[test]
    fn test_vehicle_model_identifiers_with_engine_displacement() {
        assert!(VehicleSchemaV1::validate_identifier("golf-1.5tsi"));
        assert!(VehicleSchemaV1::validate_identifier("f-150-3.5-ecoboost"));
    }

    #[test]
    fn test_validate_identifier_passes_for_slug_strings() {
        assert!(VehicleSchemaV1::validate_identifier("ford"));
        assert!(VehicleSchemaV1::validate_identifier("model-3"));
        assert!(VehicleSchemaV1::validate_identifier("golf-1.5tsi"));
        assert!(VehicleSchemaV1::validate_identifier("2020"));
        assert!(VehicleSchemaV1::validate_identifier("a1-b2-c3"));
    }

    #[test]
    fn test_validate_identifier_fails_for_non_slug_strings() {
        assert!(!VehicleSchemaV1::validate_identifier("Outback XT"));
        assert!(!VehicleSchemaV1::validate_identifier("model_3"));
        assert!(!VehicleSchemaV1::validate_identifier("model+3"));
        assert!(!VehicleSchemaV1::validate_identifier("model--3"));
        assert!(!VehicleSchemaV1::validate_identifier("/model3"));
        assert!(!VehicleSchemaV1::validate_identifier(""));
        assert!(!VehicleSchemaV1::validate_identifier("-model"));
    }

    #[test]
    fn test_build_filepath_output() {
        let base = std::path::Path::new("/tmp/vehicles-db");
        let schema = sample_schema();
        let actual = schema.build_filepath(base, "yaml");
        let expected = base.join("v1/fastsim-3/conv/ford/fusion/2012/base/r1.yaml");
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_build_url_output() {
        let schema = sample_schema();
        let actual = schema.build_url(None, "yaml");
        let expected =
            "https://raw.githubusercontent.com/NatLabRockies/fastsim-vehicles/main/v1/fastsim-3/conv/ford/fusion/2012/base/r1.yaml"
                .to_string();
        assert_eq!(actual, expected);
    }
}