Skip to main content

acde_wire/
channel.rs

1use serde_json::{Value, json};
2
3#[cfg(unix)]
4mod unix;
5#[cfg(unix)]
6pub use unix::{Channel, FdKeeper, Packet, Received, handed, pair};
7
8pub const API_LEVEL: u32 = parse_level(include_str!("../acde-api/api-level"));
9pub const MIN_API_LEVEL: u32 = parse_level(include_str!("../acde-api/min-api-level"));
10
11pub fn speaks(level: u64) -> bool {
12    (u64::from(MIN_API_LEVEL)..=u64::from(API_LEVEL)).contains(&level)
13}
14
15pub fn levels() -> String {
16    if MIN_API_LEVEL == API_LEVEL { format!("level {API_LEVEL}") } else { format!("levels {MIN_API_LEVEL} to {API_LEVEL}") }
17}
18
19const fn parse_level(text: &str) -> u32 {
20    let bytes = text.as_bytes();
21    let mut level = 0;
22    let mut i = 0;
23    while i < bytes.len() {
24        if bytes[i].is_ascii_digit() {
25            level = level * 10 + (bytes[i] - b'0') as u32;
26        }
27        i += 1;
28    }
29    level
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct Refusal {
34    pub status: u16,
35    pub code: &'static str,
36    pub message: String,
37    pub retry_after_ms: Option<u64>,
38}
39
40impl Refusal {
41    pub fn bad_request(message: impl Into<String>) -> Self {
42        Self { status: 400, code: "bad_request", message: message.into(), retry_after_ms: None }
43    }
44
45    pub fn forbidden(message: impl Into<String>) -> Self {
46        Self { status: 403, code: "forbidden", message: message.into(), retry_after_ms: None }
47    }
48
49    pub fn not_found(message: impl Into<String>) -> Self {
50        Self { status: 404, code: "not_found", message: message.into(), retry_after_ms: None }
51    }
52
53    pub fn conflict(code: &'static str, message: impl Into<String>) -> Self {
54        Self { status: 409, code, message: message.into(), retry_after_ms: None }
55    }
56
57    pub fn unsupported(service: &str, method: &str) -> Self {
58        Self { status: 501, code: "unsupported", message: format!("{service}.{method} is not supported by the session's manager yet"), retry_after_ms: None }
59    }
60
61    pub fn unavailable(message: impl Into<String>) -> Self {
62        Self { status: 503, code: "unavailable", message: message.into(), retry_after_ms: None }
63    }
64
65    pub fn to_json(&self) -> Value {
66        let mut refusal = json!({ "status": self.status, "code": self.code, "message": self.message });
67        if let Some(ms) = self.retry_after_ms {
68            refusal["retryAfterMs"] = json!(ms);
69            refusal["retryAfter"] = json!(ms.div_ceil(1000).max(1));
70        }
71        refusal
72    }
73}
74
75#[derive(Debug, PartialEq)]
76pub enum Frame {
77    Hello { api: u32, pid: u32, dev_key: Option<String> },
78    Call { id: u64, service: String, method: String, args: Vec<Value> },
79    Answer { id: u64, result: Result<Value, Value> },
80    Ready { provides: serde_json::Map<String, Value> },
81    Invoke { function: u64, args: Value },
82    Release { function: u64 },
83    DevResponse { id: u64, ok: bool, payload: String },
84    DevEvent { text: String },
85    DevTools { port: u64 },
86    DevInject { event: Value },
87    DevWindow { change: Value },
88    Panels { user_only: Vec<[i32; 4]> },
89}
90
91impl Frame {
92    pub fn parse(value: Value) -> Result<Self, String> {
93        if let Some(hello) = value.get("hello") {
94            let api = hello.get("api").and_then(Value::as_u64).ok_or("hello needs api")?;
95            let pid = hello.get("pid").and_then(Value::as_u64).unwrap_or(0);
96            let dev_key = hello.get("dev_key").and_then(Value::as_str).map(String::from);
97            return Ok(Frame::Hello { api: api as u32, pid: pid as u32, dev_key });
98        }
99        if let Some(ready) = value.get("ready") {
100            let provides = ready.get("provides").and_then(Value::as_object).cloned().ok_or("ready needs provides")?;
101            return Ok(Frame::Ready { provides });
102        }
103        let function = |frame: &Value| frame.get("fn").and_then(Value::as_u64).ok_or("needs a numeric fn");
104        if let Some(invoke) = value.get("invoke") {
105            return Ok(Frame::Invoke { function: function(invoke)?, args: invoke.get("args").cloned().unwrap_or(Value::Array(Vec::new())) });
106        }
107        if let Some(release) = value.get("release") {
108            return Ok(Frame::Release { function: function(release)? });
109        }
110        if let Some(response) = value.get("devresponse") {
111            let id = response.get("id").and_then(Value::as_u64).ok_or("devresponse needs a numeric id")?;
112            let ok = response.get("ok").and_then(Value::as_bool).unwrap_or(false);
113            let payload = response.get("payload").and_then(Value::as_str).unwrap_or_default().to_string();
114            return Ok(Frame::DevResponse { id, ok, payload });
115        }
116        if let Some(text) = value.get("devevent") {
117            return Ok(Frame::DevEvent { text: text.as_str().ok_or("devevent is JSON text")?.to_string() });
118        }
119        if let Some(change) = value.get("devwindow") {
120            return Ok(Frame::DevWindow { change: change.clone() });
121        }
122        if let Some(event) = value.get("devinject") {
123            return Ok(Frame::DevInject { event: event.clone() });
124        }
125        if let Some(panels) = value.get("panels") {
126            let rects = panels.get("user_only").and_then(Value::as_array).ok_or("panels needs user_only")?;
127            let rect = |r: &Value| -> Option<[i32; 4]> {
128                let r = r.as_array().filter(|r| r.len() == 4)?;
129                let n = |i: usize| r[i].as_i64().and_then(|v| i32::try_from(v).ok());
130                Some([n(0)?, n(1)?, n(2)?, n(3)?])
131            };
132            let user_only = rects.iter().map(rect).collect::<Option<Vec<_>>>().ok_or("panels: each rect is [x, y, width, height]")?;
133            return Ok(Frame::Panels { user_only });
134        }
135        if let Some(devtools) = value.get("devtools") {
136            return Ok(Frame::DevTools { port: devtools.get("port").and_then(Value::as_u64).ok_or("devtools needs a port")? });
137        }
138        let id = value.get("id").and_then(Value::as_u64).ok_or("a call needs a numeric id")?;
139        if value.get("service").is_none() {
140            if let Some(error) = value.get("error") {
141                return Ok(Frame::Answer { id, result: Err(error.clone()) });
142            }
143            if let Some(ok) = value.get("ok") {
144                return Ok(Frame::Answer { id, result: Ok(ok.clone()) });
145            }
146        }
147        let text = |key: &str| value.get(key).and_then(Value::as_str).map(String::from).ok_or_else(|| format!("call {id} needs {key}"));
148        let args = match value.get("args") {
149            None | Some(Value::Null) => Vec::new(),
150            Some(Value::Array(args)) => args.clone(),
151            Some(_) => return Err(format!("call {id}: args is an array")),
152        };
153        Ok(Frame::Call { id, service: text("service")?, method: text("method")?, args })
154    }
155}
156
157pub fn answer(id: u64, result: Result<Value, Refusal>) -> Value {
158    match result {
159        Ok(ok) => json!({ "id": id, "ok": ok }),
160        Err(refusal) => json!({ "id": id, "error": refusal.to_json() }),
161    }
162}
163
164pub fn event(event: Value) -> Value {
165    json!({ "event": event })
166}
167
168pub fn base64(bytes: &[u8]) -> String {
169    const DIGITS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
170    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
171    for chunk in bytes.chunks(3) {
172        let n = chunk.iter().enumerate().fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i));
173        for i in 0..4 {
174            out.push(if i <= chunk.len() { DIGITS[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' });
175        }
176    }
177    out
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn refusals_round_trip_as_answer_frames() {
186        let refusal = Refusal::unsupported("settings", "reset");
187        assert_eq!(Frame::parse(answer(7, Err(refusal.clone()))), Ok(Frame::Answer { id: 7, result: Err(refusal.to_json()) }));
188    }
189
190    #[test]
191    fn base64_pads_like_rfc_4648() {
192        assert_eq!(base64(b""), "");
193        assert_eq!(base64(b"f"), "Zg==");
194        assert_eq!(base64(b"fo"), "Zm8=");
195        assert_eq!(base64(b"foo"), "Zm9v");
196        assert_eq!(base64(b"foobar"), "Zm9vYmFy");
197    }
198}