Skip to main content

schedr_model/
version.rs

1//! The schedr version that produced a piece of stored data, and which versions can read it.
2//!
3//! Within a major version, changes to DAG JSON (and the protocol, the API, stored outputs) are
4//! additive only, so a reader accepts data of the same major and an equal or lower minor
5//! version (see archive/PROJECT.md, Upgrades and compatibility).
6
7use std::borrow::Cow;
8use std::fmt;
9use std::str::FromStr;
10
11use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
12use serde::{Deserialize, Serialize};
13
14#[cfg(test)]
15mod tests;
16
17/// A schedr version as `major.minor`; the patch level never changes compatibility.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
19#[serde(try_from = "String", into = "String")]
20pub struct SchedrVersion {
21    /// The major version: data of another major version is never read.
22    pub major: u32,
23    /// The minor version: a reader reads data of an equal or lower minor version.
24    pub minor: u32,
25}
26
27/// Why a string isn't a valid schedr version.
28#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
29#[error("`{0}` is not a schedr version (expected `major.minor` or `major.minor.patch`)")]
30pub struct VersionError(pub String);
31
32impl SchedrVersion {
33    /// Creates a version from its parts.
34    #[must_use]
35    pub const fn new(major: u32, minor: u32) -> Self {
36        Self { major, minor }
37    }
38
39    /// The version of this build of schedr.
40    ///
41    /// # Panics
42    ///
43    /// Never in practice: the crate version is checked by a unit test.
44    #[must_use]
45    pub fn current() -> Self {
46        env!("CARGO_PKG_VERSION")
47            .parse()
48            .expect("the crate version is a valid schedr version")
49    }
50
51    /// Whether this version can read data produced by `produced`: the same major and an equal
52    /// or lower minor version.
53    #[must_use]
54    pub const fn can_read(self, produced: Self) -> bool {
55        self.major == produced.major && produced.minor <= self.minor
56    }
57}
58
59impl fmt::Display for SchedrVersion {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        write!(f, "{}.{}", self.major, self.minor)
62    }
63}
64
65impl FromStr for SchedrVersion {
66    type Err = VersionError;
67
68    /// Parses `major.minor` or `major.minor.patch` (the patch level, including any
69    /// pre-release suffix, is ignored).
70    fn from_str(s: &str) -> Result<Self, Self::Err> {
71        let error = || VersionError(s.to_owned());
72        let mut parts = s.split('.');
73        let major = parts
74            .next()
75            .and_then(|p| p.parse().ok())
76            .ok_or_else(error)?;
77        let minor = parts
78            .next()
79            .and_then(|p| p.parse().ok())
80            .ok_or_else(error)?;
81        match (parts.next(), parts.next()) {
82            (None, None) => {}
83            (Some(patch), None) if !patch.is_empty() => {}
84            _ => return Err(error()),
85        }
86        Ok(Self { major, minor })
87    }
88}
89
90impl TryFrom<String> for SchedrVersion {
91    type Error = VersionError;
92
93    fn try_from(s: String) -> Result<Self, Self::Error> {
94        s.parse()
95    }
96}
97
98impl From<SchedrVersion> for String {
99    fn from(v: SchedrVersion) -> Self {
100        v.to_string()
101    }
102}
103
104impl JsonSchema for SchedrVersion {
105    fn schema_name() -> Cow<'static, str> {
106        "SchedrVersion".into()
107    }
108
109    fn json_schema(_: &mut SchemaGenerator) -> Schema {
110        json_schema!({
111            "type": "string",
112            "pattern": r"^[0-9]+\.[0-9]+$",
113            "description": "A schedr version as `major.minor`.",
114        })
115    }
116}