qualia_client_core/identity_plane/
device.rs1use crate::setup::DeviceContext;
4use serde::{Deserialize, Serialize};
5use std::time::{SystemTime, UNIX_EPOCH};
6
7fn now_unix() -> u64 {
8 SystemTime::now()
9 .duration_since(UNIX_EPOCH)
10 .map(|d| d.as_secs())
11 .unwrap_or(0)
12}
13
14#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
16pub struct DeviceCapabilities {
17 #[serde(default = "default_true")]
19 pub local_jobs: bool,
20 #[serde(default = "default_true")]
22 pub inference: bool,
23 #[serde(default)]
25 pub mesh_transport: bool,
26}
27
28fn default_true() -> bool {
29 true
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
34pub struct DeviceRecord {
35 pub device_id: String,
37 pub person_id: String,
39 pub identity_pubkey_hex: String,
41 #[serde(default)]
43 pub label: String,
44 #[serde(default)]
46 pub hostname: String,
47 #[serde(default)]
49 pub device_context: DeviceContext,
50 pub capabilities: DeviceCapabilities,
51 #[serde(default)]
54 pub control_base_url: String,
55 pub is_local: bool,
57 pub created_at_unix: u64,
58 pub last_seen_unix: u64,
59}
60
61pub type DeviceRecordPublic = DeviceRecord;
63
64impl DeviceRecord {
65 pub fn device_did_from_pubkey_hex(pubkey_hex: &str) -> String {
67 format!("did:q42:device:{}", pubkey_hex.trim().to_ascii_lowercase())
68 }
69
70 pub fn new_local(
72 person_id: impl Into<String>,
73 identity_pubkey_hex: impl Into<String>,
74 device_context: DeviceContext,
75 label: impl Into<String>,
76 ) -> Self {
77 let identity_pubkey_hex = identity_pubkey_hex.into().to_ascii_lowercase();
78 let device_id = Self::device_did_from_pubkey_hex(&identity_pubkey_hex);
79 let now = now_unix();
80 let hostname = hostname_best_effort();
81 Self {
82 device_id,
83 person_id: person_id.into(),
84 identity_pubkey_hex,
85 label: label.into(),
86 hostname,
87 device_context,
88 capabilities: DeviceCapabilities {
89 local_jobs: true,
90 inference: true,
91 mesh_transport: true,
92 },
93 control_base_url: String::new(),
94 is_local: true,
95 created_at_unix: now,
96 last_seen_unix: now,
97 }
98 }
99
100 pub fn touch(&mut self) {
102 self.last_seen_unix = now_unix();
103 }
104
105 pub fn with_control_base_url(mut self, url: impl Into<String>) -> Self {
107 self.control_base_url = url.into().trim().trim_end_matches('/').to_string();
108 self
109 }
110}
111
112fn hostname_best_effort() -> String {
113 std::env::var("COMPUTERNAME")
114 .or_else(|_| std::env::var("HOSTNAME"))
115 .unwrap_or_default()
116}
117
118#[cfg(test)]
119mod tests {
120 use super::*;
121
122 #[test]
123 fn device_id_is_not_person_id_shape() {
124 let d = DeviceRecord::new_local(
125 "did:q42:person:aabb",
126 "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff",
127 DeviceContext::default(),
128 "desk",
129 );
130 assert!(d.device_id.starts_with("did:q42:device:"));
131 assert!(!d.device_id.starts_with("did:q42:person:"));
132 assert_ne!(d.device_id, d.person_id);
133 }
134}