common/version.rs
1// version information for protocol compatibility checking
2
3use serde::{Deserialize, Serialize};
4
5/// Protocol version information
6///
7/// Contains version information for compatibility checking between rcp and rcpd.
8/// The semantic version is used for compatibility checks, while git information
9/// provides additional debugging context.
10#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
11pub struct ProtocolVersion {
12 /// Semantic version from Cargo.toml (e.g., "0.22.0")
13 ///
14 /// This is the primary version used for compatibility checking.
15 pub semantic: String,
16
17 /// Git describe output (e.g., "v0.21.1-7-g644da27")
18 ///
19 /// Optional. Provides detailed version information including:
20 /// - Most recent tag
21 /// - Number of commits since tag
22 /// - Short commit hash
23 /// - "-dirty" suffix if working tree has uncommitted changes
24 #[serde(skip_serializing_if = "Option::is_none")]
25 pub git_describe: Option<String>,
26
27 /// Full git commit hash
28 ///
29 /// Optional. Useful for exact build identification and debugging.
30 #[serde(skip_serializing_if = "Option::is_none")]
31 pub git_hash: Option<String>,
32}
33
34/// The remote protocol/process-contract revision, carried INSIDE [`ProtocolVersion::semantic`] as
35/// semver build metadata (`0.38.0+w1`) rather than as a separate field — deliberately, for symmetry:
36/// the compatibility check is a string equality on `semantic`, so a build predating this constant
37/// rejects a current one exactly as a current build rejects it ("0.38.0" != "0.38.0+w1"), no
38/// matter which side was upgraded first. A separate field would protect only the new side — an old
39/// parser ignores unknown JSON fields and could accept a changed serialized or spawn contract.
40///
41/// Bump this on any wire-visible change to `remote/src/protocol` OR a version-sensitive rcpd spawn
42/// argument change whenever the crate version does not also change. The crate version alone cannot
43/// tell two 0.38.0-dev builds apart, so a stale same-version `rcpd` (on `PATH` or in the deploy
44/// cache) would otherwise pass compatibility and then fail or misbehave mid-copy.
45/// Revision 11 adds the receiver copy-buffer retention limit to daemon startup arguments.
46pub const WIRE_REVISION: u32 = 11;
47
48impl ProtocolVersion {
49 /// Get the current protocol version
50 ///
51 /// Reads version information from environment variables set at compile time
52 /// by build.rs. The semantic version is always available, while git information
53 /// may be absent if the build was done without git available.
54 pub fn current() -> Self {
55 Self {
56 semantic: format!("{}+w{}", env!("CARGO_PKG_VERSION"), WIRE_REVISION),
57 git_describe: option_env!("RCP_GIT_DESCRIBE").map(String::from),
58 git_hash: option_env!("RCP_GIT_HASH").map(String::from),
59 }
60 }
61
62 /// The crate version alone — `semantic` with the `+w<revision>` build metadata stripped.
63 /// This is what user-facing remedies quote (`cargo install --version <this>`); the wire
64 /// revision is not a cargo version.
65 pub fn crate_version(&self) -> &str {
66 self.semantic.split('+').next().unwrap_or(&self.semantic)
67 }
68
69 /// Check if this version is compatible with another version
70 ///
71 /// Currently implements exact version matching: versions are compatible
72 /// only if their semantic versions match exactly.
73 ///
74 /// # Examples
75 ///
76 /// ```
77 /// use common::version::ProtocolVersion;
78 ///
79 /// let v1 = ProtocolVersion {
80 /// semantic: "0.22.0".to_string(),
81 /// git_describe: None,
82 /// git_hash: None,
83 /// };
84 ///
85 /// let v2 = ProtocolVersion {
86 /// semantic: "0.22.0".to_string(),
87 /// git_describe: Some("v0.21.1-7-g644da27".to_string()),
88 /// git_hash: None,
89 /// };
90 ///
91 /// assert!(v1.is_compatible_with(&v2));
92 /// ```
93 pub fn is_compatible_with(&self, other: &Self) -> bool {
94 // exact version match for now
95 // in the future, we might allow minor version skew (e.g., 0.22.x compatible with 0.22.y).
96 // `semantic` embeds the remote compatibility revision as build metadata (see
97 // wire revision), so this one string equality also rejects two same-release builds
98 // straddling a protocol/process-contract change — in BOTH directions, including a peer
99 // built before the revision existed.
100 self.semantic == other.semantic
101 }
102
103 /// The deployed-binary cache filename component for this version: the semantic string with
104 /// its `+` made filename-friendly (`0.38.0+w1` → `0.38.0-w1`).
105 ///
106 /// One string for BOTH the discovery probe and the deploy target, so an incompatible
107 /// same-release cached binary is never found (its filename carries the old revision) and a
108 /// fresh deploy never overwrites a binary another compatibility revision still resolves to.
109 pub fn cache_tag(&self) -> String {
110 self.semantic.replace('+', "-")
111 }
112
113 /// Get a human-readable version string
114 ///
115 /// Returns the semantic version, optionally including git describe information
116 /// if available.
117 ///
118 /// # Examples
119 ///
120 /// ```
121 /// use common::version::ProtocolVersion;
122 ///
123 /// let v = ProtocolVersion {
124 /// semantic: "0.22.0".to_string(),
125 /// git_describe: Some("v0.21.1-7-g644da27".to_string()),
126 /// git_hash: None,
127 /// };
128 ///
129 /// assert_eq!(v.display(), "0.22.0 (v0.21.1-7-g644da27)");
130 /// ```
131 pub fn display(&self) -> String {
132 if let Some(ref git_describe) = self.git_describe {
133 format!("{} ({})", self.semantic, git_describe)
134 } else {
135 self.semantic.clone()
136 }
137 }
138
139 /// Serialize to JSON string
140 ///
141 /// # Errors
142 ///
143 /// Returns an error if JSON serialization fails.
144 pub fn to_json(&self) -> anyhow::Result<String> {
145 serde_json::to_string(self)
146 .map_err(|e| anyhow::anyhow!("failed to serialize version: {:#}", e))
147 }
148
149 /// Deserialize from JSON string
150 ///
151 /// # Errors
152 ///
153 /// Returns an error if JSON deserialization fails or the format is invalid.
154 pub fn from_json(json: &str) -> anyhow::Result<Self> {
155 serde_json::from_str(json)
156 .map_err(|e| anyhow::anyhow!("failed to parse version JSON: {:#}", e))
157 }
158}
159
160impl std::fmt::Display for ProtocolVersion {
161 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162 write!(f, "{}", self.display())
163 }
164}
165
166#[cfg(test)]
167mod tests {
168 use super::*;
169
170 #[cfg_attr(rcp_nix_sandbox, ignore = "Nix source build has no Git metadata")]
171 #[test]
172 fn test_current_version() {
173 let version = ProtocolVersion::current();
174 // semantic version should always be available
175 assert!(!version.semantic.is_empty());
176 // git info should be available when building from git repository
177 // this test will catch if build.rs is not activated in Cargo.toml
178 assert!(
179 version.git_describe.is_some(),
180 "git_describe should be populated by build.rs (check that build.rs is activated in Cargo.toml)"
181 );
182 assert!(
183 version.git_hash.is_some(),
184 "git_hash should be populated by build.rs (check that build.rs is activated in Cargo.toml)"
185 );
186 }
187
188 #[test]
189 fn test_exact_version_compatibility() {
190 let v1 = ProtocolVersion {
191 semantic: "0.22.0".to_string(),
192 git_describe: None,
193 git_hash: None,
194 };
195
196 let v2 = ProtocolVersion {
197 semantic: "0.22.0".to_string(),
198 git_describe: Some("v0.21.1-7-g644da27".to_string()),
199 git_hash: Some("644da27".to_string()),
200 };
201
202 let v3 = ProtocolVersion {
203 semantic: "0.21.0".to_string(),
204 git_describe: None,
205 git_hash: None,
206 };
207
208 // same semantic version should be compatible
209 assert!(v1.is_compatible_with(&v2));
210 assert!(v2.is_compatible_with(&v1));
211
212 // different semantic versions should not be compatible
213 assert!(!v1.is_compatible_with(&v3));
214 assert!(!v3.is_compatible_with(&v1));
215 }
216
217 #[test]
218 fn test_display() {
219 let v1 = ProtocolVersion {
220 semantic: "0.22.0".to_string(),
221 git_describe: None,
222 git_hash: None,
223 };
224 assert_eq!(v1.display(), "0.22.0");
225
226 let v2 = ProtocolVersion {
227 semantic: "0.22.0".to_string(),
228 git_describe: Some("v0.21.1-7-g644da27".to_string()),
229 git_hash: None,
230 };
231 assert_eq!(v2.display(), "0.22.0 (v0.21.1-7-g644da27)");
232 }
233
234 #[test]
235 fn wire_revision_mismatch_is_incompatible_in_both_directions() {
236 let a = ProtocolVersion::current();
237 assert!(a.is_compatible_with(&a.clone()));
238 assert!(
239 a.semantic.contains("+w"),
240 "the compatibility revision must ride inside `semantic`, where even a pre-revision peer's string comparison sees it"
241 );
242 let mut b = a.clone();
243 b.semantic = format!("{}+w{}", a.crate_version(), WIRE_REVISION + 1);
244 assert!(
245 !a.is_compatible_with(&b),
246 "same release with a different remote protocol/process contract must be rejected"
247 );
248 // a build predating the revision reports the bare crate version; the SAME string
249 // equality both sides have always used rejects it — symmetry is the point
250 let legacy = ProtocolVersion {
251 semantic: a.crate_version().to_string(),
252 git_describe: None,
253 git_hash: None,
254 };
255 assert!(!a.is_compatible_with(&legacy));
256 assert!(!legacy.is_compatible_with(&a));
257 assert_eq!(a.cache_tag(), a.semantic.replace('+', "-"));
258 }
259
260 #[test]
261 fn current_contract_rejects_daemons_without_required_startup_arguments() {
262 let current = ProtocolVersion::current();
263 for revision in [8, 9, 10] {
264 let previous = ProtocolVersion {
265 semantic: format!("{}+w{revision}", current.crate_version()),
266 git_describe: None,
267 git_hash: None,
268 };
269 assert!(!current.is_compatible_with(&previous));
270 assert!(!previous.is_compatible_with(¤t));
271 assert_ne!(current.cache_tag(), previous.cache_tag());
272 }
273 }
274
275 #[test]
276 fn test_json_serialization() {
277 let v = ProtocolVersion {
278 semantic: "0.22.0".to_string(),
279 git_describe: Some("v0.21.1-7-g644da27".to_string()),
280 git_hash: Some("644da27abc".to_string()),
281 };
282
283 let json = v.to_json().unwrap();
284 let parsed = ProtocolVersion::from_json(&json).unwrap();
285
286 assert_eq!(v, parsed);
287 }
288
289 #[test]
290 fn test_json_deserialization_without_git() {
291 let json = r#"{"semantic":"0.22.0"}"#;
292 let v = ProtocolVersion::from_json(json).unwrap();
293
294 assert_eq!(v.semantic, "0.22.0");
295 assert!(v.git_describe.is_none());
296 assert!(v.git_hash.is_none());
297 }
298}