Skip to main content

hyprstream_workers/dbus/
protocol.rs

1//! D-Bus bridge protocol types
2//!
3//! Defines the request/response types for the D-Bus proxy protocol.
4//! These are serialized via JSON for simplicity (can be upgraded to Cap'n Proto later).
5
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8
9/// D-Bus bus type
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(rename_all = "lowercase")]
12#[derive(Default)]
13pub enum BusType {
14    /// System bus (/var/run/dbus/system_bus_socket)
15    System,
16    /// Session bus ($DBUS_SESSION_BUS_ADDRESS)
17    #[default]
18    Session,
19}
20
21impl std::fmt::Display for BusType {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        match self {
24            BusType::System => write!(f, "system"),
25            BusType::Session => write!(f, "session"),
26        }
27    }
28}
29
30/// D-Bus value types supported by the bridge
31///
32/// A simplified subset of D-Bus types for common use cases.
33#[derive(Debug, Clone, Serialize, Deserialize)]
34#[serde(untagged)]
35pub enum DbusValue {
36    /// String value
37    String(String),
38    /// Boolean value
39    Bool(bool),
40    /// Signed 32-bit integer
41    Int32(i32),
42    /// Unsigned 32-bit integer
43    Uint32(u32),
44    /// Signed 64-bit integer
45    Int64(i64),
46    /// Unsigned 64-bit integer
47    Uint64(u64),
48    /// Double-precision float
49    Double(f64),
50    /// Array of values
51    Array(Vec<DbusValue>),
52    /// Dictionary (a{sv} style)
53    Dict(HashMap<String, DbusValue>),
54    /// Byte array (useful for binary data)
55    Bytes(Vec<u8>),
56    /// Object path
57    ObjectPath(String),
58    /// Variant (boxed value)
59    Variant(Box<DbusValue>),
60}
61
62impl DbusValue {
63    /// Create a string value
64    pub fn string(s: impl Into<String>) -> Self {
65        DbusValue::String(s.into())
66    }
67
68    /// Create an object path value
69    pub fn object_path(path: impl Into<String>) -> Self {
70        DbusValue::ObjectPath(path.into())
71    }
72
73    /// Create a variant value
74    pub fn variant(inner: DbusValue) -> Self {
75        DbusValue::Variant(Box::new(inner))
76    }
77
78    /// Try to get as string
79    pub fn as_str(&self) -> Option<&str> {
80        match self {
81            DbusValue::String(s) | DbusValue::ObjectPath(s) => Some(s),
82            _ => None,
83        }
84    }
85
86    /// Try to get as i64
87    pub fn as_i64(&self) -> Option<i64> {
88        match self {
89            DbusValue::Int32(n) => Some(*n as i64),
90            DbusValue::Int64(n) => Some(*n),
91            DbusValue::Uint32(n) => Some(*n as i64),
92            _ => None,
93        }
94    }
95
96    /// Try to get as bool
97    pub fn as_bool(&self) -> Option<bool> {
98        match self {
99            DbusValue::Bool(b) => Some(*b),
100            _ => None,
101        }
102    }
103}
104
105/// Request to call a D-Bus method
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct DbusCallRequest {
108    /// Bus to use (system or session)
109    #[serde(default)]
110    pub bus: BusType,
111
112    /// Destination bus name (e.g., "org.freedesktop.Notifications")
113    pub destination: String,
114
115    /// Object path (e.g., "/org/freedesktop/Notifications")
116    pub path: String,
117
118    /// Interface name (e.g., "org.freedesktop.Notifications")
119    pub interface: String,
120
121    /// Method name (e.g., "Notify")
122    pub method: String,
123
124    /// Method arguments
125    #[serde(default)]
126    pub args: Vec<DbusValue>,
127
128    /// Timeout in milliseconds (0 = default)
129    #[serde(default)]
130    pub timeout_ms: u32,
131}
132
133impl DbusCallRequest {
134    /// Create a new method call request
135    pub fn new(
136        destination: impl Into<String>,
137        path: impl Into<String>,
138        interface: impl Into<String>,
139        method: impl Into<String>,
140    ) -> Self {
141        Self {
142            bus: BusType::Session,
143            destination: destination.into(),
144            path: path.into(),
145            interface: interface.into(),
146            method: method.into(),
147            args: Vec::new(),
148            timeout_ms: 0,
149        }
150    }
151
152    /// Set the bus type
153    pub fn bus(mut self, bus: BusType) -> Self {
154        self.bus = bus;
155        self
156    }
157
158    /// Add an argument
159    pub fn arg(mut self, value: DbusValue) -> Self {
160        self.args.push(value);
161        self
162    }
163
164    /// Set timeout
165    pub fn timeout(mut self, ms: u32) -> Self {
166        self.timeout_ms = ms;
167        self
168    }
169}
170
171/// Request to get a D-Bus property
172#[derive(Debug, Clone, Serialize, Deserialize)]
173pub struct DbusGetPropertyRequest {
174    /// Bus to use
175    #[serde(default)]
176    pub bus: BusType,
177
178    /// Destination bus name
179    pub destination: String,
180
181    /// Object path
182    pub path: String,
183
184    /// Interface containing the property
185    pub interface: String,
186
187    /// Property name
188    pub property: String,
189}
190
191/// Request to set a D-Bus property
192#[derive(Debug, Clone, Serialize, Deserialize)]
193pub struct DbusSetPropertyRequest {
194    /// Bus to use
195    #[serde(default)]
196    pub bus: BusType,
197
198    /// Destination bus name
199    pub destination: String,
200
201    /// Object path
202    pub path: String,
203
204    /// Interface containing the property
205    pub interface: String,
206
207    /// Property name
208    pub property: String,
209
210    /// New value
211    pub value: DbusValue,
212}
213
214/// Request to subscribe to a D-Bus signal
215#[derive(Debug, Clone, Serialize, Deserialize)]
216pub struct DbusSubscribeRequest {
217    /// Bus to use
218    #[serde(default)]
219    pub bus: BusType,
220
221    /// Sender filter (optional)
222    #[serde(default)]
223    pub sender: Option<String>,
224
225    /// Object path filter (optional)
226    #[serde(default)]
227    pub path: Option<String>,
228
229    /// Interface filter
230    pub interface: String,
231
232    /// Signal name filter
233    pub signal: String,
234}
235
236/// Response from a D-Bus method call
237#[derive(Debug, Clone, Serialize, Deserialize)]
238pub struct DbusCallResponse {
239    /// Return values from the method
240    pub values: Vec<DbusValue>,
241}
242
243impl DbusCallResponse {
244    /// Create a response with values
245    pub fn new(values: Vec<DbusValue>) -> Self {
246        Self { values }
247    }
248
249    /// Create an empty response
250    pub fn empty() -> Self {
251        Self { values: Vec::new() }
252    }
253
254    /// Get the first return value
255    pub fn first(&self) -> Option<&DbusValue> {
256        self.values.first()
257    }
258}
259
260/// D-Bus error response
261#[derive(Debug, Clone, Serialize, Deserialize)]
262pub struct DbusError {
263    /// Error name (e.g., "org.freedesktop.DBus.Error.ServiceUnknown")
264    pub name: String,
265
266    /// Error message
267    pub message: String,
268}
269
270impl DbusError {
271    /// Create a new D-Bus error
272    pub fn new(name: impl Into<String>, message: impl Into<String>) -> Self {
273        Self {
274            name: name.into(),
275            message: message.into(),
276        }
277    }
278
279    /// Create an access denied error
280    pub fn access_denied(resource: &str) -> Self {
281        Self::new(
282            "org.freedesktop.DBus.Error.AccessDenied",
283            format!("Access denied to {resource}"),
284        )
285    }
286
287    /// Create a service unknown error
288    pub fn service_unknown(service: &str) -> Self {
289        Self::new(
290            "org.freedesktop.DBus.Error.ServiceUnknown",
291            format!("Service {service} is not available"),
292        )
293    }
294
295    /// Create a method not found error
296    pub fn method_not_found(interface: &str, method: &str) -> Self {
297        Self::new(
298            "org.freedesktop.DBus.Error.UnknownMethod",
299            format!("Method {interface}.{method} not found"),
300        )
301    }
302}
303
304impl std::fmt::Display for DbusError {
305    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
306        write!(f, "{}: {}", self.name, self.message)
307    }
308}
309
310impl std::error::Error for DbusError {}
311
312/// Signal received from D-Bus
313#[derive(Debug, Clone, Serialize, Deserialize)]
314pub struct DbusSignal {
315    /// Sender bus name
316    pub sender: String,
317
318    /// Object path
319    pub path: String,
320
321    /// Interface name
322    pub interface: String,
323
324    /// Signal name
325    pub signal: String,
326
327    /// Signal arguments
328    pub args: Vec<DbusValue>,
329}
330
331/// Unified D-Bus request type
332#[derive(Debug, Clone, Serialize, Deserialize)]
333#[serde(tag = "type", rename_all = "snake_case")]
334pub enum DbusRequest {
335    /// Call a method
336    Call(DbusCallRequest),
337
338    /// Get a property
339    GetProperty(DbusGetPropertyRequest),
340
341    /// Set a property
342    SetProperty(DbusSetPropertyRequest),
343
344    /// Subscribe to a signal
345    Subscribe(DbusSubscribeRequest),
346
347    /// Unsubscribe from signals
348    Unsubscribe {
349        /// Subscription ID to cancel
350        subscription_id: String,
351    },
352}
353
354/// Unified D-Bus response type
355#[derive(Debug, Clone, Serialize, Deserialize)]
356#[serde(tag = "type", rename_all = "snake_case")]
357pub enum DbusResponse {
358    /// Method call response
359    Return(DbusCallResponse),
360
361    /// Property value
362    Property { value: DbusValue },
363
364    /// Subscription created
365    Subscribed {
366        /// Subscription ID for tracking
367        subscription_id: String,
368    },
369
370    /// Unsubscribed
371    Unsubscribed,
372
373    /// Error response
374    Error(DbusError),
375}
376
377impl DbusResponse {
378    /// Create a return response
379    pub fn return_values(values: Vec<DbusValue>) -> Self {
380        DbusResponse::Return(DbusCallResponse::new(values))
381    }
382
383    /// Create an error response
384    pub fn error(name: impl Into<String>, message: impl Into<String>) -> Self {
385        DbusResponse::Error(DbusError::new(name, message))
386    }
387
388    /// Create an access denied response
389    pub fn access_denied(resource: &str) -> Self {
390        DbusResponse::Error(DbusError::access_denied(resource))
391    }
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397
398    #[test]
399    fn test_dbus_value_serialization() -> serde_json::Result<()> {
400        let value = DbusValue::Dict(HashMap::from([
401            ("app_name".to_owned(), DbusValue::String("test".to_owned())),
402            ("urgency".to_owned(), DbusValue::Uint32(1)),
403        ]));
404
405        let json = serde_json::to_string(&value)?;
406        let parsed: DbusValue = serde_json::from_str(&json)?;
407
408        match parsed {
409            DbusValue::Dict(map) => {
410                assert!(map.contains_key("app_name"));
411                assert!(map.contains_key("urgency"));
412            }
413            _ => panic!("Expected Dict"),
414        }
415        Ok(())
416    }
417
418    #[test]
419    fn test_call_request_builder() {
420        let request = DbusCallRequest::new(
421            "org.freedesktop.Notifications",
422            "/org/freedesktop/Notifications",
423            "org.freedesktop.Notifications",
424            "Notify",
425        )
426        .bus(BusType::Session)
427        .arg(DbusValue::String("app".to_owned()))
428        .arg(DbusValue::Uint32(0))
429        .timeout(5000);
430
431        assert_eq!(request.method, "Notify");
432        assert_eq!(request.args.len(), 2);
433        assert_eq!(request.timeout_ms, 5000);
434    }
435
436    #[test]
437    fn test_request_serialization() -> serde_json::Result<()> {
438        let request = DbusRequest::Call(DbusCallRequest::new(
439            "org.example.Service",
440            "/org/example/Object",
441            "org.example.Interface",
442            "Method",
443        ));
444
445        let json = serde_json::to_string(&request)?;
446        assert!(json.contains("\"type\":\"call\""));
447
448        let parsed: DbusRequest = serde_json::from_str(&json)?;
449        match parsed {
450            DbusRequest::Call(call) => {
451                assert_eq!(call.destination, "org.example.Service");
452            }
453            _ => panic!("Expected Call"),
454        }
455        Ok(())
456    }
457
458    #[test]
459    fn test_response_serialization() -> serde_json::Result<()> {
460        let response = DbusResponse::return_values(vec![DbusValue::Uint32(42)]);
461
462        let json = serde_json::to_string(&response)?;
463        assert!(json.contains("\"type\":\"return\""));
464        Ok(())
465    }
466
467    #[test]
468    fn test_error_creation() {
469        let err = DbusError::access_denied("dbus:session:org.example:Method");
470        assert!(err.name.contains("AccessDenied"));
471        assert!(err.message.contains("org.example"));
472    }
473}