garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /ui/src/verbs.rs

raw

//! Asking a service what it can do, and asking it to do it
//! (`pinnacle_records::verbs`): what the terminal's commands and the agent's
//! gatekeeper both use, so a verb the person runs and one the agent asks
//! for are the same message on the same channel.

use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_json::Value;
use pinnacle_records::verbs::{self, CALL, DESCRIBE, DESCRIPTION, Description, Pieces, RESULT};
use pinnacle_rt::{Channel, Handle, Received};

/// The services that describe themselves, and what each is for.
pub const SERVICES: &[(&str, &str)] = &[("p2p", "Your contacts and the messages with them")];

/// What the person calls a service: the app it stands for.
pub fn title(service: &str) -> String {
    match service {
        "p2p" => "Messages".into(),
        other => crate::theme::display_name(other),
    }
}

/// How long a service may take to answer. A verb that works longer (a
/// build) answers at once with a job and is asked again for its end.
pub const TIMEOUT: u64 = 60_000;

/// Sends `kind` with `json` on `channel`, in pieces; `handles` with the last.
pub fn send(channel: &Channel, kind: u8, json: &str, handles: Vec<Handle>) -> bool {
    let mut pieces = verbs::pieces(kind, json);
    let last = pieces.pop().unwrap();
    pieces.iter().all(|p| channel.send(p, Vec::new())) && channel.send(&last, handles)
}

/// Waits for a whole message of `kind` on `channel`, setting aside any
/// other the service sends meanwhile.
fn answer(channel: &Channel, kind: u8, timeout: u64) -> Option<Value> {
    let until = pinnacle_rt::time() + timeout;
    let mut pieces = Pieces::default();
    let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
    loop {
        match pinnacle_rt::receive(&[channel], &mut buffer, Some(until)) {
            Received::Message { len, .. } => {
                if let Some((k, value)) = pieces.push(&buffer[..len])
                    && k == kind
                {
                    return Some(value);
                }
            }
            _ => return None,
        }
    }
}

/// What the service on `channel` can do.
pub fn describe_on(channel: &Channel) -> Option<Description> {
    send(channel, DESCRIBE, "", Vec::new());
    Description::from_json(&answer(channel, DESCRIPTION, TIMEOUT)?)
}

/// What the service registered as `service` can do (`name@contact` on a
/// contact's device).
pub fn describe(service: &str) -> Option<(Channel, Description)> {
    let channel = crate::command::connect_service(service)?;
    let description = describe_on(&channel)?;
    Some((channel, description))
}

/// Calls `verb` with `args` on `channel`; `handles` go with it.
pub fn call(channel: &Channel, verb: &str, args: Value, handles: Vec<Handle>) -> verbs::Result {
    let body = alloc::format!("{}", verbs::call(verb, args));
    if !send(channel, CALL, &body, handles) {
        return verbs::Result::error("the service is gone");
    }
    answer(channel, RESULT, TIMEOUT)
        .and_then(|v| verbs::Result::from_json(&v))
        .unwrap_or_else(|| verbs::Result::error("the service did not answer"))
}

/// A service's side: what a message on a client's channel asks, once whole.
pub enum Request {
    Describe,
    Call { verb: String, args: Value },
}

impl Request {
    /// Reads a client's message into `pieces`; a request once it is whole.
    pub fn read(pieces: &mut Pieces, message: &[u8]) -> Option<Request> {
        match pieces.push(message)? {
            (DESCRIBE, _) => Some(Request::Describe),
            (CALL, v) => Some(Request::Call {
                verb: v.get("verb").as_str()?.into(),
                args: v.get("args").clone(),
            }),
            _ => None,
        }
    }
}

/// Answers a [`Request::Describe`].
pub fn describe_to(client: &Channel, description: &Description) -> bool {
    send(
        client,
        DESCRIPTION,
        &alloc::format!("{}", description.to_json()),
        Vec::new(),
    )
}

/// Answers a [`Request::Call`]: checks the arguments against the verb first,
/// so `run` sees only well-typed calls of verbs the service described.
pub fn serve_call(
    client: &Channel,
    description: &Description,
    verb: &str,
    args: &Value,
    run: impl FnOnce(&str, &Value) -> verbs::Result,
) -> bool {
    let result = match description.verb(verb) {
        None => verbs::Result::error(&alloc::format!("{} has no verb “{verb}”", description.service)),
        Some(v) => match v.check(args) {
            Err(why) => verbs::Result::error(&why),
            Ok(()) => run(verb, args),
        },
    };
    send(
        client,
        RESULT,
        &alloc::format!("{}", result.to_json()),
        Vec::new(),
    )
}

/// `key=value` words, a value in double quotes when it has spaces, as a
/// command line gives them; typed by the verb's parameters (a number or a
/// yes/no where the verb takes one). The reason when they are not.
pub fn parse_args(verb: &verbs::Verb, text: &str) -> Result<Value, String> {
    let mut fields = Vec::new();
    let mut rest = text.trim_start();
    while !rest.is_empty() {
        let (name, after) = rest
            .split_once('=')
            .ok_or_else(|| alloc::format!("“{}” is not name=value", rest.split(' ').next().unwrap_or("")))?;
        let (value, after) = match after.strip_prefix('"') {
            Some(quoted) => {
                let end = quoted.find('"').ok_or("a quote is not closed")?;
                (&quoted[..end], &quoted[end + 1..])
            }
            None => after.split_once(' ').unwrap_or((after, "")),
        };
        let name = name.trim();
        let typed = match verb.params.iter().find(|p| p.name == name).map(|p| p.kind) {
            Some(verbs::Type::Number) => value
                .parse::<i64>()
                .map(Value::from)
                .map_err(|_| alloc::format!("{name} must be a number"))?,
            Some(verbs::Type::Bool) => match value {
                "yes" | "true" => Value::Bool(true),
                "no" | "false" => Value::Bool(false),
                _ => return Err(alloc::format!("{name} must be yes or no")),
            },
            _ => Value::from(value),
        };
        fields.push((String::from(name), typed));
        rest = after.trim_start();
    }
    let args = Value::Object(fields);
    verb.check(&args)?;
    Ok(args)
}