acde-wire 1.1.10

The session manager's control channel (JSON frames with fds) and the acompositor client protocols, for acdes and acdev's guest agent
Documentation
use serde_json::{Value, json};

#[cfg(unix)]
mod unix;
#[cfg(unix)]
pub use unix::{Channel, FdKeeper, Packet, Received, handed, pair};

pub const API_LEVEL: u32 = parse_level(include_str!("../acde-api/api-level"));
pub const MIN_API_LEVEL: u32 = parse_level(include_str!("../acde-api/min-api-level"));

pub fn speaks(level: u64) -> bool {
    (u64::from(MIN_API_LEVEL)..=u64::from(API_LEVEL)).contains(&level)
}

pub fn levels() -> String {
    if MIN_API_LEVEL == API_LEVEL { format!("level {API_LEVEL}") } else { format!("levels {MIN_API_LEVEL} to {API_LEVEL}") }
}

const fn parse_level(text: &str) -> u32 {
    let bytes = text.as_bytes();
    let mut level = 0;
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i].is_ascii_digit() {
            level = level * 10 + (bytes[i] - b'0') as u32;
        }
        i += 1;
    }
    level
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refusal {
    pub status: u16,
    pub code: &'static str,
    pub message: String,
    pub retry_after_ms: Option<u64>,
}

impl Refusal {
    pub fn bad_request(message: impl Into<String>) -> Self {
        Self { status: 400, code: "bad_request", message: message.into(), retry_after_ms: None }
    }

    pub fn forbidden(message: impl Into<String>) -> Self {
        Self { status: 403, code: "forbidden", message: message.into(), retry_after_ms: None }
    }

    pub fn not_found(message: impl Into<String>) -> Self {
        Self { status: 404, code: "not_found", message: message.into(), retry_after_ms: None }
    }

    pub fn conflict(code: &'static str, message: impl Into<String>) -> Self {
        Self { status: 409, code, message: message.into(), retry_after_ms: None }
    }

    pub fn unsupported(service: &str, method: &str) -> Self {
        Self { status: 501, code: "unsupported", message: format!("{service}.{method} is not supported by the session's manager yet"), retry_after_ms: None }
    }

    pub fn unavailable(message: impl Into<String>) -> Self {
        Self { status: 503, code: "unavailable", message: message.into(), retry_after_ms: None }
    }

    pub fn to_json(&self) -> Value {
        let mut refusal = json!({ "status": self.status, "code": self.code, "message": self.message });
        if let Some(ms) = self.retry_after_ms {
            refusal["retryAfterMs"] = json!(ms);
            refusal["retryAfter"] = json!(ms.div_ceil(1000).max(1));
        }
        refusal
    }
}

#[derive(Debug, PartialEq)]
pub enum Frame {
    Hello { api: u32, pid: u32, dev_key: Option<String> },
    Call { id: u64, service: String, method: String, args: Vec<Value> },
    Answer { id: u64, result: Result<Value, Value> },
    Ready { provides: serde_json::Map<String, Value> },
    Invoke { function: u64, args: Value },
    Release { function: u64 },
    DevResponse { id: u64, ok: bool, payload: String },
    DevEvent { text: String },
    DevTools { port: u64 },
    DevInject { event: Value },
    DevWindow { change: Value },
    Panels { user_only: Vec<[i32; 4]> },
}

impl Frame {
    pub fn parse(value: Value) -> Result<Self, String> {
        if let Some(hello) = value.get("hello") {
            let api = hello.get("api").and_then(Value::as_u64).ok_or("hello needs api")?;
            let pid = hello.get("pid").and_then(Value::as_u64).unwrap_or(0);
            let dev_key = hello.get("dev_key").and_then(Value::as_str).map(String::from);
            return Ok(Frame::Hello { api: api as u32, pid: pid as u32, dev_key });
        }
        if let Some(ready) = value.get("ready") {
            let provides = ready.get("provides").and_then(Value::as_object).cloned().ok_or("ready needs provides")?;
            return Ok(Frame::Ready { provides });
        }
        let function = |frame: &Value| frame.get("fn").and_then(Value::as_u64).ok_or("needs a numeric fn");
        if let Some(invoke) = value.get("invoke") {
            return Ok(Frame::Invoke { function: function(invoke)?, args: invoke.get("args").cloned().unwrap_or(Value::Array(Vec::new())) });
        }
        if let Some(release) = value.get("release") {
            return Ok(Frame::Release { function: function(release)? });
        }
        if let Some(response) = value.get("devresponse") {
            let id = response.get("id").and_then(Value::as_u64).ok_or("devresponse needs a numeric id")?;
            let ok = response.get("ok").and_then(Value::as_bool).unwrap_or(false);
            let payload = response.get("payload").and_then(Value::as_str).unwrap_or_default().to_string();
            return Ok(Frame::DevResponse { id, ok, payload });
        }
        if let Some(text) = value.get("devevent") {
            return Ok(Frame::DevEvent { text: text.as_str().ok_or("devevent is JSON text")?.to_string() });
        }
        if let Some(change) = value.get("devwindow") {
            return Ok(Frame::DevWindow { change: change.clone() });
        }
        if let Some(event) = value.get("devinject") {
            return Ok(Frame::DevInject { event: event.clone() });
        }
        if let Some(panels) = value.get("panels") {
            let rects = panels.get("user_only").and_then(Value::as_array).ok_or("panels needs user_only")?;
            let rect = |r: &Value| -> Option<[i32; 4]> {
                let r = r.as_array().filter(|r| r.len() == 4)?;
                let n = |i: usize| r[i].as_i64().and_then(|v| i32::try_from(v).ok());
                Some([n(0)?, n(1)?, n(2)?, n(3)?])
            };
            let user_only = rects.iter().map(rect).collect::<Option<Vec<_>>>().ok_or("panels: each rect is [x, y, width, height]")?;
            return Ok(Frame::Panels { user_only });
        }
        if let Some(devtools) = value.get("devtools") {
            return Ok(Frame::DevTools { port: devtools.get("port").and_then(Value::as_u64).ok_or("devtools needs a port")? });
        }
        let id = value.get("id").and_then(Value::as_u64).ok_or("a call needs a numeric id")?;
        if value.get("service").is_none() {
            if let Some(error) = value.get("error") {
                return Ok(Frame::Answer { id, result: Err(error.clone()) });
            }
            if let Some(ok) = value.get("ok") {
                return Ok(Frame::Answer { id, result: Ok(ok.clone()) });
            }
        }
        let text = |key: &str| value.get(key).and_then(Value::as_str).map(String::from).ok_or_else(|| format!("call {id} needs {key}"));
        let args = match value.get("args") {
            None | Some(Value::Null) => Vec::new(),
            Some(Value::Array(args)) => args.clone(),
            Some(_) => return Err(format!("call {id}: args is an array")),
        };
        Ok(Frame::Call { id, service: text("service")?, method: text("method")?, args })
    }
}

pub fn answer(id: u64, result: Result<Value, Refusal>) -> Value {
    match result {
        Ok(ok) => json!({ "id": id, "ok": ok }),
        Err(refusal) => json!({ "id": id, "error": refusal.to_json() }),
    }
}

pub fn event(event: Value) -> Value {
    json!({ "event": event })
}

pub fn base64(bytes: &[u8]) -> String {
    const DIGITS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let n = chunk.iter().enumerate().fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i));
        for i in 0..4 {
            out.push(if i <= chunk.len() { DIGITS[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' });
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn refusals_round_trip_as_answer_frames() {
        let refusal = Refusal::unsupported("settings", "reset");
        assert_eq!(Frame::parse(answer(7, Err(refusal.clone()))), Ok(Frame::Answer { id: 7, result: Err(refusal.to_json()) }));
    }

    #[test]
    fn base64_pads_like_rfc_4648() {
        assert_eq!(base64(b""), "");
        assert_eq!(base64(b"f"), "Zg==");
        assert_eq!(base64(b"fo"), "Zm8=");
        assert_eq!(base64(b"foo"), "Zm9v");
        assert_eq!(base64(b"foobar"), "Zm9vYmFy");
    }
}