Skip to main content

orch/store/cluster/
version.rs

1//! The orch version of each node. Nodes apply the same commands to their own schema, so an older
2//! node must not apply what a newer one wrote
3
4use std::fmt;
5use std::fmt::Display;
6use std::fmt::Formatter;
7use std::str::FromStr;
8use std::sync::Mutex;
9use std::sync::PoisonError;
10
11use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
12use tokio::sync::watch;
13
14/// Major, minor and patch. A pre-release or build suffix is dropped, so `1.2.3-rc1` is `1.2.3`
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub struct Version(pub u64, pub u64, pub u64);
17
18impl Version {
19    /// The version this binary was built as
20    pub fn current() -> Self {
21        env!("CARGO_PKG_VERSION").parse().unwrap_or(Self(0, 0, 0))
22    }
23}
24
25impl Display for Version {
26    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
27        write!(f, "{}.{}.{}", self.0, self.1, self.2)
28    }
29}
30
31impl FromStr for Version {
32    type Err = String;
33
34    fn from_str(s: &str) -> Result<Self, String> {
35        let core = s
36            .trim()
37            .trim_start_matches('v')
38            .split(['-', '+'])
39            .next()
40            .unwrap_or_default();
41        let mut parts = core.split('.').map(str::parse::<u64>);
42        match (parts.next(), parts.next(), parts.next(), parts.next()) {
43            (Some(Ok(a)), Some(Ok(b)), Some(Ok(c)), None) => Ok(Self(a, b, c)),
44            _ => Err(format!("not a version: {s:?}")),
45        }
46    }
47}
48
49impl Serialize for Version {
50    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
51        s.collect_str(self)
52    }
53}
54
55impl<'de> Deserialize<'de> for Version {
56    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
57        let s = String::deserialize(d)?;
58        s.parse().map_err(de::Error::custom)
59    }
60}
61
62/// True when a node on `mine` may apply what `stamp` wrote. No stamp is older than any version
63pub fn may_apply(mine: Version, stamp: Option<Version>) -> bool {
64    stamp.is_none_or(|v| v <= mine)
65}
66
67/**
68 * What one node knows about versions: its own, the newer version an entry or snapshot asked for
69 * once the node stopped applying, and the highest version a peer that proved the secret reported.
70 * `mine` is None on a single node, which checks nothing
71 **/
72#[derive(Debug)]
73pub struct Versions {
74    mine: Option<Version>,
75    needs: watch::Sender<Option<Version>>,
76    highest_peer: Mutex<Option<Version>>,
77}
78
79impl Versions {
80    pub fn new(mine: Option<Version>) -> Self {
81        Self {
82            mine,
83            needs: watch::Sender::new(None),
84            highest_peer: Mutex::new(None),
85        }
86    }
87
88    pub fn mine(&self) -> Option<Version> {
89        self.mine
90    }
91
92    /// The version this node must run before it applies again, or None while it applies
93    pub fn needs_upgrade(&self) -> Option<Version> {
94        *self.needs.borrow()
95    }
96
97    pub(crate) fn hold(&self, needed: Version) {
98        self.needs.send_if_modified(|cur| {
99            let next = cur.map_or(needed, |c| c.max(needed));
100            let changed = *cur != Some(next);
101            *cur = Some(next);
102            changed
103        });
104    }
105
106    pub(crate) fn subscribe(&self) -> watch::Receiver<Option<Version>> {
107        self.needs.subscribe()
108    }
109
110    /// Record a version a peer reported after it proved the secret
111    pub fn saw_peer(&self, v: Version) {
112        let mut highest = self
113            .highest_peer
114            .lock()
115            .unwrap_or_else(PoisonError::into_inner);
116        if highest.is_none_or(|h| v > h) {
117            *highest = Some(v);
118        }
119    }
120
121    /// The highest version any peer that proved the secret reported
122    pub fn highest_peer(&self) -> Option<Version> {
123        *self
124            .highest_peer
125            .lock()
126            .unwrap_or_else(PoisonError::into_inner)
127    }
128}