1use std::collections::BTreeMap;
26
27use serde::{Deserialize, Serialize};
28
29pub const DISCOVERY_PATH: &str = "/.well-known/recall";
31
32pub const PROTOCOL: u32 = 1;
34
35pub const PROTOCOL_HEADER: &str = "recall-protocol";
39
40#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
42pub struct Discovery {
43 pub protocol: Protocol,
45 pub server: ServerInfo,
47 pub min_client: String,
49 pub auth: Auth,
51 #[serde(default)]
53 pub capabilities: BTreeMap<String, serde_json::Value>,
54}
55
56impl Discovery {
57 pub fn speaks(&self, version: u32) -> bool {
59 self.protocol.supported.contains(&version)
60 }
61
62 pub fn can(&self, name: &str) -> bool {
64 self.capabilities.contains_key(name)
65 }
66
67 pub fn accepts(&self, name: &str) -> bool {
70 self.auth.methods.iter().any(|m| m == name)
71 }
72
73 pub fn devices(&self) -> Option<crate::DevicesCapability> {
77 serde_json::from_value(self.capabilities.get(CAPABILITY_DEVICES)?.clone()).ok()
78 }
79
80 pub fn audit(&self) -> Option<crate::AuditCapability> {
84 serde_json::from_value(self.capabilities.get(CAPABILITY_AUDIT)?.clone()).ok()
85 }
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90pub struct Protocol {
91 pub current: u32,
93 pub supported: Vec<u32>,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
99pub struct ServerInfo {
100 pub version: String,
103 pub build: Build,
105}
106
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109pub struct Build {
110 pub channel: String,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
114 pub revision: Option<String>,
115 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub created: Option<String>,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122pub struct Auth {
123 pub methods: Vec<String>,
125}
126
127pub const AUTH_BEARER: &str = "bearer";
129
130pub const AUTH_DEVICE_SIG: &str = "device-sig-v1";
133
134pub const CAPABILITY_DEVICES: &str = "devices";
137
138pub const CAPABILITY_MERGE_QUEUE: &str = "merge_queue";
142
143pub const CAPABILITY_EVALUATION: &str = "evaluation";
146
147pub const CAPABILITY_AUDIT: &str = "audit";
151
152pub const CHANNEL_RELEASE: &str = "release";
154
155pub const CHANNEL_DEV: &str = "dev";
158
159pub fn channel() -> &'static str {
165 match env!("RECALL_RESOLVED_CHANNEL") {
166 CHANNEL_RELEASE => CHANNEL_RELEASE,
167 _ => CHANNEL_DEV,
168 }
169}
170
171pub fn revision() -> Option<&'static str> {
173 option_env!("RECALL_GIT_COMMIT").filter(|r| !r.is_empty())
174}
175
176pub fn created() -> Option<&'static str> {
179 option_env!("RECALL_BUILD_CREATED").filter(|c| !c.is_empty())
180}
181
182pub fn version() -> String {
184 version_for(channel(), revision())
185}
186
187pub fn version_for(channel: &str, revision: Option<&str>) -> String {
195 let base = env!("CARGO_PKG_VERSION");
196 if channel == CHANNEL_RELEASE {
197 return base.to_string();
198 }
199 let next = match Version::parse(base) {
200 Some(v) => format!("{}.{}.{}", v.major, v.minor, v.patch + 1),
201 None => base.to_string(),
202 };
203 match revision {
204 Some(rev) => {
205 let short: String = rev.chars().take(7).collect();
206 format!("{next}-dev+g{short}")
207 }
208 None => format!("{next}-dev"),
209 }
210}
211
212pub fn user_agent() -> String {
215 format!(
216 "recall/{} ({}-{})",
217 version(),
218 std::env::consts::OS,
219 std::env::consts::ARCH
220 )
221}
222
223#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct Version {
229 pub major: u64,
231 pub minor: u64,
233 pub patch: u64,
235 pub pre: Vec<String>,
237}
238
239impl Version {
240 pub fn parse(text: &str) -> Option<Self> {
243 let text = text.trim().trim_start_matches('v');
244 let text = text.split('+').next()?;
245 let (core, pre) = match text.split_once('-') {
246 Some((core, pre)) => (core, pre.split('.').map(str::to_string).collect()),
247 None => (text, Vec::new()),
248 };
249 let mut parts = core.split('.');
250 let major = parts.next()?.parse().ok()?;
251 let minor = parts.next()?.parse().ok()?;
252 let patch = parts.next()?.parse().ok()?;
253 if parts.next().is_some() {
254 return None;
255 }
256 Some(Self {
257 major,
258 minor,
259 patch,
260 pre,
261 })
262 }
263}
264
265impl PartialOrd for Version {
266 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
267 Some(self.cmp(other))
268 }
269}
270
271impl Ord for Version {
272 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
277 use std::cmp::Ordering;
278 let core =
279 (self.major, self.minor, self.patch).cmp(&(other.major, other.minor, other.patch));
280 if core != Ordering::Equal {
281 return core;
282 }
283 match (self.pre.is_empty(), other.pre.is_empty()) {
284 (true, true) => return Ordering::Equal,
285 (true, false) => return Ordering::Greater,
286 (false, true) => return Ordering::Less,
287 (false, false) => {}
288 }
289 for (a, b) in self.pre.iter().zip(&other.pre) {
290 let order = match (a.parse::<u64>(), b.parse::<u64>()) {
291 (Ok(x), Ok(y)) => x.cmp(&y),
292 (Ok(_), Err(_)) => Ordering::Less,
293 (Err(_), Ok(_)) => Ordering::Greater,
294 (Err(_), Err(_)) => a.cmp(b),
295 };
296 if order != Ordering::Equal {
297 return order;
298 }
299 }
300 self.pre.len().cmp(&other.pre.len())
301 }
302}
303
304#[cfg(test)]
305mod tests {
306 use super::*;
307
308 fn v(text: &str) -> Version {
309 Version::parse(text).unwrap()
310 }
311
312 #[test]
314 fn versions_order_the_way_semver_says() {
315 let ordered = [
316 "1.0.0-alpha",
317 "1.0.0-alpha.1",
318 "1.0.0-alpha.beta",
319 "1.0.0-beta",
320 "1.0.0-beta.2",
321 "1.0.0-beta.11",
322 "1.0.0-rc.1",
323 "1.0.0",
324 "2.0.0",
325 "2.1.0",
326 "2.1.1",
327 ];
328 for pair in ordered.windows(2) {
329 assert!(v(pair[0]) < v(pair[1]), "{} < {}", pair[0], pair[1]);
330 }
331 }
332
333 #[test]
334 fn build_metadata_does_not_count() {
335 assert_eq!(v("0.3.3-dev+g1a2b3c4"), v("0.3.3-dev+gffffff0"));
336 assert!(v("0.3.2") < v("0.3.3-dev+g1a2b3c4"));
337 assert!(v("0.3.3-dev+g1a2b3c4") < v("0.3.3"));
338 }
339
340 #[test]
341 fn what_is_not_a_version_is_refused() {
342 for bad in ["", "1", "1.2", "1.2.3.4", "a.b.c", "1.2.x"] {
343 assert_eq!(Version::parse(bad), None, "{bad:?}");
344 }
345 assert_eq!(v("v1.2.3"), v("1.2.3"));
346 }
347
348 #[test]
349 fn a_release_build_is_its_release_and_anything_else_the_next_dev() {
350 let base = env!("CARGO_PKG_VERSION");
351 assert_eq!(version_for(CHANNEL_RELEASE, Some("abc")), base);
352 let dev = version_for(CHANNEL_DEV, Some("e100cfdd88e8a0e6659b"));
353 assert!(dev.ends_with("-dev+ge100cfd"), "{dev}");
354 assert!(v(base) < v(&dev), "{base} < {dev}");
355 assert!(version_for(CHANNEL_DEV, None).ends_with("-dev"));
356 }
357
358 #[test]
361 fn unknown_keys_are_ignored_and_absent_capabilities_are_unsupported() {
362 let doc: Discovery = serde_json::from_str(
363 r#"{
364 "protocol": {"current": 2, "supported": [1, 2]},
365 "server": {"version": "0.9.0", "build": {"channel": "release", "signed": true}},
366 "min_client": "0.3.0",
367 "auth": {"methods": ["device-sig-v1", "bearer"]},
368 "capabilities": {"merge_base": {}, "telepathy": {"level": 3}},
369 "operator": {"contact": "someone"}
370 }"#,
371 )
372 .unwrap();
373 assert!(doc.speaks(1) && doc.speaks(2) && !doc.speaks(3));
374 assert!(doc.can("merge_base") && doc.can("telepathy"));
375 assert!(!doc.can("scopes"));
376 assert!(doc.accepts(AUTH_DEVICE_SIG) && doc.accepts(AUTH_BEARER));
377 assert!(!doc.accepts("passkey"));
378 assert_eq!(doc.devices(), None, "not listed, so not supported");
379 }
380
381 #[test]
384 fn the_devices_capability_reads_into_its_type() {
385 let mut doc: Discovery = serde_json::from_str(
386 r#"{
387 "protocol": {"current": 1, "supported": [1]},
388 "server": {"version": "0.4.1", "build": {"channel": "release"}},
389 "min_client": "0.1.0",
390 "auth": {"methods": ["bearer", "device-sig-v1"]},
391 "capabilities": {"devices": {
392 "enroll_path": "/v1/devices/enroll", "code_ttl_seconds": 900,
393 "poll_interval_seconds": 5, "signature_window_seconds": 60,
394 "passkeys": {}
395 }}
396 }"#,
397 )
398 .unwrap();
399 let devices = doc.devices().unwrap();
400 assert_eq!(devices.enroll_path, "/v1/devices/enroll");
401 assert_eq!(devices.signature_window_seconds, 60);
402
403 doc.capabilities.insert(
404 CAPABILITY_DEVICES.into(),
405 serde_json::json!({"enroll_path": "/x"}),
406 );
407 assert_eq!(doc.devices(), None);
408 }
409
410 #[test]
411 fn the_user_agent_names_the_version_and_platform() {
412 let ua = user_agent();
413 assert!(ua.starts_with("recall/"), "{ua}");
414 assert!(ua.contains(std::env::consts::OS), "{ua}");
415 }
416}