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    auto_upgrade: bool,
78    upgrade_error: Mutex<Option<String>>,
79}
80
81impl Versions {
82    pub fn new(mine: Option<Version>) -> Self {
83        Self {
84            mine,
85            needs: watch::Sender::new(None),
86            highest_peer: Mutex::new(None),
87            auto_upgrade: false,
88            upgrade_error: Mutex::new(None),
89        }
90    }
91
92    /// `cluster.auto_upgrade`: the node upgrades itself to the highest version in the cluster
93    #[must_use]
94    pub fn with_auto_upgrade(mut self, on: bool) -> Self {
95        self.auto_upgrade = on;
96        self
97    }
98
99    pub fn auto_upgrade(&self) -> bool {
100        self.auto_upgrade
101    }
102
103    /// Why the last upgrade failed, or None
104    pub fn upgrade_error(&self) -> Option<String> {
105        self.upgrade_error
106            .lock()
107            .unwrap_or_else(PoisonError::into_inner)
108            .clone()
109    }
110
111    pub fn set_upgrade_error(&self, err: Option<String>) {
112        *self
113            .upgrade_error
114            .lock()
115            .unwrap_or_else(PoisonError::into_inner) = err;
116    }
117
118    /// The version this node upgrades to: the highest a peer reported or an entry asked for, when
119    /// it is above its own
120    pub fn target(&self) -> Option<Version> {
121        let mine = self.mine?;
122        let highest = self.highest_peer().max(self.needs_upgrade())?;
123        (highest > mine).then_some(highest)
124    }
125
126    pub fn mine(&self) -> Option<Version> {
127        self.mine
128    }
129
130    /// The version this node must run before it applies again, or None while it applies
131    pub fn needs_upgrade(&self) -> Option<Version> {
132        *self.needs.borrow()
133    }
134
135    pub(crate) fn hold(&self, needed: Version) {
136        self.needs.send_if_modified(|cur| {
137            let next = cur.map_or(needed, |c| c.max(needed));
138            let changed = *cur != Some(next);
139            *cur = Some(next);
140            changed
141        });
142    }
143
144    pub(crate) fn subscribe(&self) -> watch::Receiver<Option<Version>> {
145        self.needs.subscribe()
146    }
147
148    /// Record a version a peer reported after it proved the secret
149    pub fn saw_peer(&self, v: Version) {
150        let mut highest = self
151            .highest_peer
152            .lock()
153            .unwrap_or_else(PoisonError::into_inner);
154        if highest.is_none_or(|h| v > h) {
155            *highest = Some(v);
156        }
157    }
158
159    /// The highest version any peer that proved the secret reported
160    pub fn highest_peer(&self) -> Option<Version> {
161        *self
162            .highest_peer
163            .lock()
164            .unwrap_or_else(PoisonError::into_inner)
165    }
166}