acde-wire 1.1.6

The session manager's control channel (JSON frames with fds) and the acompositor client protocols, for acdes and acdev's guest agent
Documentation
use std::path::PathBuf;

use serde_json::{Map, Value, json};

pub const VERSION: u64 = 2;
pub const SAMPLE_RATE: u32 = 16_000;
pub const MAX_FRAME: usize = 1 << 20;
pub const MAX_HOTWORDS: usize = 200;
pub const MAX_HOTWORD_CHARS: usize = 32;
pub const MAX_NAME_CHARS: usize = 128;

const CONTROL: u8 = 0x01;
const AUDIO: u8 = 0x02;
const HEADER: usize = 4;

pub fn socket_path() -> Option<PathBuf> {
    let runtime = std::env::var_os("XDG_RUNTIME_DIR").filter(|dir| !dir.is_empty())?;
    Some(PathBuf::from(runtime).join("acdes").join("asr.socket"))
}

#[derive(Debug, Clone, PartialEq)]
pub enum Frame {
    Control(Value),
    Audio(Vec<i16>),
}

impl Frame {
    pub fn encode(&self) -> Vec<u8> {
        let (kind, payload) = match self {
            Frame::Control(value) => (CONTROL, value.to_string().into_bytes()),
            Frame::Audio(samples) => (AUDIO, samples.iter().flat_map(|s| s.to_le_bytes()).collect()),
        };
        let length = u32::try_from(payload.len() + 1).unwrap_or(u32::MAX);
        let mut out = Vec::with_capacity(HEADER + 1 + payload.len());
        out.extend_from_slice(&length.to_le_bytes());
        out.push(kind);
        out.extend_from_slice(&payload);
        out
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FrameError {
    TooLong(usize),
    Empty,
    Kind(u8),
    Json(String),
    OddAudio(usize),
}

impl std::fmt::Display for FrameError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FrameError::TooLong(length) => write!(f, "a frame of {length} bytes is longer than {MAX_FRAME}"),
            FrameError::Empty => write!(f, "a frame without its kind byte"),
            FrameError::Kind(kind) => write!(f, "unknown frame kind {kind:#04x}"),
            FrameError::Json(why) => write!(f, "a control frame that is no JSON object: {why}"),
            FrameError::OddAudio(length) => write!(f, "{length} bytes of audio are no whole 16-bit samples"),
        }
    }
}

#[derive(Default)]
pub struct Frames {
    buffer: Vec<u8>,
}

impl Frames {
    pub fn push(&mut self, bytes: &[u8]) {
        self.buffer.extend_from_slice(bytes);
    }

    pub fn next_frame(&mut self) -> Option<Result<Frame, FrameError>> {
        let header: [u8; HEADER] = self.buffer.get(..HEADER)?.try_into().ok()?;
        let length = u32::from_le_bytes(header) as usize;
        if length > MAX_FRAME {
            return Some(Err(FrameError::TooLong(length)));
        }
        if self.buffer.len() < HEADER + length {
            return None;
        }
        let body: Vec<u8> = self.buffer.drain(..HEADER + length).skip(HEADER).collect();
        Some(decode(&body))
    }
}

fn decode(body: &[u8]) -> Result<Frame, FrameError> {
    let (&kind, payload) = body.split_first().ok_or(FrameError::Empty)?;
    match kind {
        CONTROL => match serde_json::from_slice::<Value>(payload) {
            Ok(value) if value.is_object() => Ok(Frame::Control(value)),
            Ok(_) => Err(FrameError::Json("not an object".into())),
            Err(e) => Err(FrameError::Json(e.to_string())),
        },
        AUDIO if payload.len() % 2 == 0 => Ok(Frame::Audio(payload.chunks_exact(2).map(|b| i16::from_le_bytes([b[0], b[1]])).collect())),
        AUDIO => Err(FrameError::OddAudio(payload.len())),
        kind => Err(FrameError::Kind(kind)),
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Client {
    InputMethod,
    Voice,
}

impl Client {
    pub fn as_str(self) -> &'static str {
        match self {
            Client::InputMethod => "input-method",
            Client::Voice => "voice",
        }
    }

    pub fn parse(name: &str) -> Option<Self> {
        [Client::InputMethod, Client::Voice].into_iter().find(|client| client.as_str() == name)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Start {
    pub client: Client,
    pub hotwords: Vec<String>,
    pub recognize: bool,
    pub name: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Request {
    Hello { version: u64 },
    Start(Start),
    Finish,
    Cancel,
}

impl Request {
    pub fn to_json(&self) -> Value {
        match self {
            Request::Hello { version } => json!({ "type": "hello", "version": version }),
            Request::Start(start) => {
                let mut value = json!({ "type": "start", "client": start.client.as_str(), "hotwords": start.hotwords, "recognize": start.recognize });
                if let Some(name) = &start.name {
                    value["name"] = json!(name);
                }
                value
            }
            Request::Finish => json!({ "type": "finish" }),
            Request::Cancel => json!({ "type": "cancel" }),
        }
    }

    pub fn from_json(value: &Value) -> Result<Self, String> {
        let object = value.as_object().ok_or("a request is a JSON object")?;
        match kind_of(object)? {
            "hello" => Ok(Request::Hello { version: object.get("version").and_then(Value::as_u64).ok_or("hello needs a numeric version")? }),
            "start" => start(object).map(Request::Start),
            "finish" => Ok(Request::Finish),
            "cancel" => Ok(Request::Cancel),
            other => Err(format!("unknown request {other:?}")),
        }
    }
}

fn start(object: &Map<String, Value>) -> Result<Start, String> {
    let client = object.get("client").and_then(Value::as_str).unwrap_or_default();
    let client = Client::parse(client).ok_or_else(|| format!("start needs client input-method or voice, not {client:?}"))?;
    let recognize = match object.get("recognize") {
        None | Some(Value::Null) => true,
        Some(value) => value.as_bool().ok_or("recognize is true or false")?,
    };
    Ok(Start { client, hotwords: hotwords(object.get("hotwords"))?, recognize, name: name(object.get("name"))? })
}

fn name(value: Option<&Value>) -> Result<Option<String>, String> {
    let Some(value) = value.filter(|v| !v.is_null()) else { return Ok(None) };
    let name = value.as_str().ok_or("name is a string")?;
    let fits = !name.is_empty() && name.chars().count() <= MAX_NAME_CHARS && !name.chars().any(char::is_control);
    fits.then(|| Some(name.to_string())).ok_or_else(|| format!("name {name:?} is empty, too long or has control characters"))
}

fn hotwords(value: Option<&Value>) -> Result<Vec<String>, String> {
    let Some(value) = value.filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
    let list = value.as_array().ok_or("hotwords is a list of strings")?;
    if list.len() > MAX_HOTWORDS {
        return Err(format!("{} hotwords, at most {MAX_HOTWORDS}", list.len()));
    }
    list.iter()
        .map(|word| {
            let word = word.as_str().ok_or("hotwords is a list of strings")?.trim();
            match word.chars().count() {
                0 => Err("an empty hotword".to_string()),
                n if n > MAX_HOTWORD_CHARS => Err(format!("hotword {word:?} is longer than {MAX_HOTWORD_CHARS} characters")),
                _ => Ok(word.to_string()),
            }
        })
        .collect()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reason {
    ModelMissing,
    ModelBroken,
    RuntimeFailed,
    BadRequest,
    ServiceMissing,
    MicrophoneFailed,
}

impl Reason {
    const ALL: [(Reason, &'static str); 6] = [
        (Reason::ModelMissing, "model-missing"),
        (Reason::ModelBroken, "model-broken"),
        (Reason::RuntimeFailed, "runtime-failed"),
        (Reason::BadRequest, "bad-request"),
        (Reason::ServiceMissing, "service-missing"),
        (Reason::MicrophoneFailed, "microphone-failed"),
    ];

    pub fn as_str(self) -> &'static str {
        Self::ALL.iter().find(|(reason, _)| *reason == self).map_or("runtime-failed", |(_, name)| name)
    }

    pub fn parse(name: &str) -> Option<Self> {
        Self::ALL.iter().find(|(_, n)| *n == name).map(|(reason, _)| *reason)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Model {
    pub id: String,
    pub languages: Vec<String>,
    pub hotwords: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Reply {
    Ready(Model),
    Unavailable { reason: Reason, detail: String },
    Recording,
    Level { value: f64 },
    Partial { text: String },
    Final { text: String },
    Error { reason: Reason, detail: String },
    Done,
}

impl Reply {
    pub fn to_json(&self) -> Value {
        match self {
            Reply::Ready(m) => json!({ "type": "ready", "model": m.id, "languages": m.languages, "sampleRate": SAMPLE_RATE, "hotwords": m.hotwords }),
            Reply::Unavailable { reason, detail } => json!({ "type": "unavailable", "reason": reason.as_str(), "detail": detail }),
            Reply::Recording => json!({ "type": "recording" }),
            Reply::Level { value } => json!({ "type": "level", "value": value.clamp(0.0, 1.0) }),
            Reply::Partial { text } => json!({ "type": "partial", "text": text }),
            Reply::Final { text } => json!({ "type": "final", "text": text }),
            Reply::Error { reason, detail } => json!({ "type": "error", "reason": reason.as_str(), "detail": detail }),
            Reply::Done => json!({ "type": "done" }),
        }
    }

    pub fn from_json(value: &Value) -> Result<Self, String> {
        let object = value.as_object().ok_or("a reply is a JSON object")?;
        let text = || object.get("text").and_then(Value::as_str).map(str::to_string).ok_or("no text");
        let reason = || {
            let name = object.get("reason").and_then(Value::as_str).unwrap_or_default();
            let reason = Reason::parse(name).ok_or_else(|| format!("unknown reason {name:?}"))?;
            Ok::<_, String>((reason, object.get("detail").and_then(Value::as_str).unwrap_or_default().to_string()))
        };
        match kind_of(object)? {
            "ready" => Ok(Reply::Ready(Model {
                id: object.get("model").and_then(Value::as_str).ok_or("ready needs the model")?.to_string(),
                languages: object.get("languages").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(),
                hotwords: object.get("hotwords").and_then(Value::as_bool).unwrap_or(false),
            })),
            "unavailable" => reason().map(|(reason, detail)| Reply::Unavailable { reason, detail }),
            "recording" => Ok(Reply::Recording),
            "level" => object
                .get("value")
                .and_then(Value::as_f64)
                .map(|value| Reply::Level { value: value.clamp(0.0, 1.0) })
                .ok_or_else(|| "level needs a value".into()),
            "partial" => Ok(Reply::Partial { text: text()? }),
            "final" => Ok(Reply::Final { text: text()? }),
            "error" => reason().map(|(reason, detail)| Reply::Error { reason, detail }),
            "done" => Ok(Reply::Done),
            other => Err(format!("unknown reply {other:?}")),
        }
    }
}

fn kind_of(object: &Map<String, Value>) -> Result<&str, String> {
    object.get("type").and_then(Value::as_str).ok_or_else(|| "no type".to_string())
}

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

    fn read_all(bytes: &[u8]) -> Vec<Result<Frame, FrameError>> {
        let mut frames = Frames::default();
        let mut out = Vec::new();
        for byte in bytes {
            frames.push(std::slice::from_ref(byte));
            out.extend(frames.next_frame());
        }
        out
    }

    #[test]
    fn frames_survive_being_split_anywhere() {
        let sent = [Frame::Control(Request::Start(start(Client::Voice, vec!["Dopame".into()])).to_json()), Frame::Audio(vec![0, -1, i16::MAX, i16::MIN])];
        let bytes: Vec<u8> = sent.iter().flat_map(Frame::encode).collect();
        let got: Vec<Frame> = read_all(&bytes).into_iter().map(Result::unwrap).collect();
        assert_eq!(got, sent);
    }

    #[test]
    fn bad_frames_are_named() {
        let too_long = ((MAX_FRAME + 1) as u32).to_le_bytes();
        assert_eq!(read_all(&too_long), [Err(FrameError::TooLong(MAX_FRAME + 1))]);
        assert_eq!(read_all(&[2, 0, 0, 0, AUDIO, 1]), [Err(FrameError::OddAudio(1))]);
        assert_eq!(read_all(&[1, 0, 0, 0, 9]), [Err(FrameError::Kind(9))]);
        assert!(matches!(read_all(&[3, 0, 0, 0, CONTROL, b'[', b']']).as_slice(), [Err(FrameError::Json(_))]));
    }

    #[test]
    fn requests_and_replies_round_trip() {
        let named = Start { recognize: false, name: Some("dopame.assistant".into()), ..start(Client::Voice, Vec::new()) };
        let requests = [
            Request::Hello { version: VERSION },
            Request::Start(start(Client::InputMethod, vec!["张三".into(), "acdes".into()])),
            Request::Start(named),
            Request::Finish,
            Request::Cancel,
        ];
        for request in requests {
            assert_eq!(Request::from_json(&request.to_json()), Ok(request));
        }
        let model = Model { id: "zipformer-zh-en".into(), languages: vec!["zh".into(), "en".into()], hotwords: true };
        let replies = [
            Reply::Ready(model),
            Reply::Unavailable { reason: Reason::ModelMissing, detail: "/usr/share/acdes/asr/models".into() },
            Reply::Recording,
            Reply::Level { value: 0.25 },
            Reply::Partial { text: "你好".into() },
            Reply::Final { text: "你好 world".into() },
            Reply::Error { reason: Reason::RuntimeFailed, detail: "x".into() },
            Reply::Error { reason: Reason::MicrophoneFailed, detail: "the default source went away".into() },
            Reply::Done,
        ];
        for reply in replies {
            assert_eq!(Reply::from_json(&reply.to_json()), Ok(reply));
        }
    }

    fn start(client: Client, hotwords: Vec<String>) -> Start {
        Start { client, hotwords, recognize: true, name: None }
    }

    #[test]
    fn hotwords_are_bounded() {
        let with = |words: Vec<String>| Request::from_json(&json!({ "type": "start", "client": "voice", "hotwords": words }));
        assert_eq!(with(Vec::new()), Ok(Request::Start(start(Client::Voice, Vec::new()))));
        assert_eq!(Request::from_json(&json!({ "type": "start", "client": "voice" })), Ok(Request::Start(start(Client::Voice, Vec::new()))));
        assert!(with(vec!["x".into(); MAX_HOTWORDS + 1]).is_err());
        assert!(with(vec!["长".repeat(MAX_HOTWORD_CHARS + 1)]).is_err());
        assert!(with(vec!["  ".into()]).is_err());
    }

    #[test]
    fn a_start_names_its_client_and_may_ask_for_audio_alone() {
        assert!(Request::from_json(&json!({ "type": "start" })).is_err(), "the client is required");
        assert!(Request::from_json(&json!({ "type": "start", "client": "browser" })).is_err());
        assert!(Request::from_json(&json!({ "type": "start", "client": "voice", "recognize": "no" })).is_err());
        assert!(Request::from_json(&json!({ "type": "start", "client": "voice", "name": "a\nb" })).is_err());
        assert!(Request::from_json(&json!({ "type": "start", "client": "voice", "name": "x".repeat(MAX_NAME_CHARS + 1) })).is_err());
        let audio = Request::from_json(&json!({ "type": "start", "client": "voice", "recognize": false, "name": "dopame.assistant" }));
        assert_eq!(audio, Ok(Request::Start(Start { recognize: false, name: Some("dopame.assistant".into()), ..start(Client::Voice, Vec::new()) })));
        assert_eq!(Reply::from_json(&json!({ "type": "level", "value": 3.0 })), Ok(Reply::Level { value: 1.0 }), "a level stays within 0 to 1");
    }

    #[test]
    fn the_socket_lives_in_the_runtime_directory() {
        let path = socket_path();
        if let Some(runtime) = std::env::var_os("XDG_RUNTIME_DIR").filter(|d| !d.is_empty()) {
            assert_eq!(path, Some(PathBuf::from(runtime).join("acdes/asr.socket")));
        }
    }
}