Skip to main content

hyprstream_core/services/
typed.rs

1//! Typed response carrying JSON (human-readable) and optionally capnp (machine-readable).
2//!
3//! Used by VFS ctl files that want to return structured data — callers get JSON
4//! by default (Display impl) while internal consumers can access the capnp bytes
5//! for zero-copy deserialization.
6
7/// Typed response carrying JSON (human-readable) and optionally capnp (machine-readable).
8#[derive(Clone, Debug)]
9pub struct TypedValue {
10    /// Schema identifier, e.g. "solver.SubmitResponse".
11    pub schema: String,
12    /// JSON serialization (always present).
13    pub json: String,
14    /// Cap'n Proto bytes (present when created from capnp).
15    pub capnp: Option<Vec<u8>>,
16}
17
18impl TypedValue {
19    /// Create a TypedValue from a JSON string with a schema identifier.
20    pub fn from_json(schema: impl Into<String>, json: impl Into<String>) -> Self {
21        Self {
22            schema: schema.into(),
23            json: json.into(),
24            capnp: None,
25        }
26    }
27
28    /// Create a TypedValue with both JSON and capnp representations.
29    pub fn from_capnp(schema: impl Into<String>, json: impl Into<String>, capnp: Vec<u8>) -> Self {
30        Self {
31            schema: schema.into(),
32            json: json.into(),
33            capnp: Some(capnp),
34        }
35    }
36}
37
38impl std::fmt::Display for TypedValue {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.write_str(&self.json)
41    }
42}
43
44impl std::str::FromStr for TypedValue {
45    type Err = serde_json::Error;
46    fn from_str(s: &str) -> Result<Self, Self::Err> {
47        // Validate it's JSON, wrap as TypedValue with empty schema.
48        let _: serde_json::Value = serde_json::from_str(s)?;
49        Ok(TypedValue {
50            schema: String::new(),
51            json: s.to_owned(),
52            capnp: None,
53        })
54    }
55}
56
57#[cfg(test)]
58#[allow(clippy::unwrap_used)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn display_returns_json() {
64        let tv = TypedValue::from_json("test.Foo", r#"{"bar":42}"#);
65        assert_eq!(tv.to_string(), r#"{"bar":42}"#);
66    }
67
68    #[test]
69    fn from_str_roundtrip() {
70        let json = r#"{"key":"value"}"#;
71        let tv: TypedValue = json.parse().unwrap();
72        assert_eq!(tv.json, json);
73        assert!(tv.schema.is_empty());
74        assert!(tv.capnp.is_none());
75    }
76
77    #[test]
78    fn from_str_invalid_json() {
79        let result = "not json".parse::<TypedValue>();
80        assert!(result.is_err());
81    }
82
83    #[test]
84    fn from_capnp_has_both() {
85        let tv = TypedValue::from_capnp("test.Bar", r#"{"x":1}"#, vec![1, 2, 3]);
86        assert_eq!(tv.schema, "test.Bar");
87        assert_eq!(tv.json, r#"{"x":1}"#);
88        assert_eq!(tv.capnp, Some(vec![1, 2, 3]));
89    }
90}