Skip to main content

adk_kernel/pairing/
kinds.rs

1//! What a paired device is, and the routes a server opens to devices beside the kernel's
2//! (spec 3.3 §7.2, §10 K2).
3
4use std::fmt;
5use std::sync::Arc;
6
7use axum::http::Method;
8use serde::{Deserialize, Serialize};
9
10use super::DeviceScope;
11use crate::error::{KernelError, Result};
12
13/// What a paired device is (spec 3.3 §7.2, §10 K2): it picks the row of §7.2 a device's
14/// answers take. Whoever issues the pairing code sets it; the claim never does. A device
15/// paired without one is a remote terminal.
16///
17/// # Example
18///
19/// ```rust
20/// use adk_kernel::pairing::DeviceKind;
21///
22/// assert_eq!(serde_json::to_value(DeviceKind::Phone).unwrap(), "phone");
23/// assert_eq!("tray".parse::<DeviceKind>().unwrap(), DeviceKind::Tray);
24/// ```
25#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
26#[serde(rename_all = "camelCase")]
27#[non_exhaustive]
28pub enum DeviceKind {
29    /// The web home installed on a phone (spec 3.3 §5.4).
30    Phone,
31    /// A terminal on another machine (spec 3.3 §5.2).
32    Terminal,
33    /// The desktop tray (spec 3.3 §5.5).
34    Tray,
35}
36
37impl DeviceKind {
38    /// The kind's name: `phone`, `terminal` or `tray`.
39    pub fn as_str(self) -> &'static str {
40        match self {
41            Self::Phone => "phone",
42            Self::Terminal => "terminal",
43            Self::Tray => "tray",
44        }
45    }
46}
47
48impl fmt::Display for DeviceKind {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        f.write_str(self.as_str())
51    }
52}
53
54impl std::str::FromStr for DeviceKind {
55    type Err = KernelError;
56
57    fn from_str(text: &str) -> Result<Self> {
58        match text.trim().to_ascii_lowercase().as_str() {
59            "phone" => Ok(Self::Phone),
60            "terminal" => Ok(Self::Terminal),
61            "tray" => Ok(Self::Tray),
62            other => Err(KernelError::Config {
63                reason: format!("unknown device kind `{other}`: use phone, terminal or tray"),
64            }),
65        }
66    }
67}
68
69/// The device scope a server's own routes need, consulted after the kernel's
70/// [`device_scope_for`](super::device_scope_for): the server names its surface routes, so the
71/// kernel never does. `None` closes a route to devices.
72///
73/// # Example
74///
75/// ```rust
76/// use std::sync::Arc;
77/// use axum::http::Method;
78/// use adk_kernel::pairing::{DeviceRoutes, DeviceScope};
79///
80/// let routes: DeviceRoutes = Arc::new(|method: &Method, path: &str| {
81///     (method == Method::GET && path.starts_with("/api/surface/")).then_some(DeviceScope::Read)
82/// });
83/// assert_eq!(routes(&Method::GET, "/api/surface/status"), Some(DeviceScope::Read));
84/// ```
85pub type DeviceRoutes = Arc<dyn Fn(&Method, &str) -> Option<DeviceScope> + Send + Sync>;