dce-cli 1.8.0

A cli routable protocol implementation for dce-router
Documentation
use bytes::Bytes;
use std::{collections::HashMap, env::args, io::{self, Read}, ops::{Deref, DerefMut}, sync::{Arc, LazyLock, RwLock}, vec};

#[cfg(not(feature = "sync"))]
use async_trait::async_trait;

use dce_router::{context::Context, protocol::{RoutableProtocol, RpMeta}, router::{RouteMatch, Router}};
use dce_util::result::{DceError, DceResult};

const MARK_PASSED_SEPARATOR: &str   = "--";
const MARK_ASSIGNMENT: &str         = "=";
const MARK_ARG_PREFIX: &str         = "-";

enum ArgType {
    AssignExpr(String, String),
    PrefixName,
    Path,
    PassedSeparator,
}

impl ArgType {
    fn parse(arg: &str) -> Self {
        let mut parts = arg.splitn(2, MARK_ASSIGNMENT);
        if let (Some(left), Some(right)) = (parts.next(), parts.next()) {
            ArgType::AssignExpr(left.to_string(), right.to_string())
        } else if arg.starts_with(MARK_ARG_PREFIX) {
            if arg == MARK_PASSED_SEPARATOR { return ArgType::PassedSeparator }
            ArgType::PrefixName
        } else {
            ArgType::Path
        }
    }
}

struct CliArgs(HashMap<String, Vec<String>>);

impl CliArgs {
    fn set_value(&mut self, key: String, value: String) {
        if let Some(vectors) = self.0.get_mut(key.as_str()) {
            vectors.push(value);
        } else {
            self.0.insert(key, vec![value]);
        }
    }
}

pub struct CliProtocol {
    meta: RpMeta<()>,
    script_path: String,
    forward_args: Vec<String>,
	path: String,
	args: CliArgs,
}

impl Deref for CliProtocol {
    type Target = RpMeta<()>;

    fn deref(&self) -> &Self::Target {
        &self.meta
    }
}

impl DerefMut for CliProtocol {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.meta
    }
}

impl CliProtocol {
    pub fn script_path(&self) -> &str {
        &self.script_path
    }

    pub fn forward_args(&self) -> &Vec<String> {
        &self.forward_args
    }

    pub fn args_map(&self) -> &HashMap<String, Vec<String>> {
        &self.args.0
    }

    pub fn args(&self, key: &str) -> Vec<&str> {
        self.args.0.get(key).map_or_else(|| vec![], |vs| vs.iter().map(|v| v.as_str()).collect::<Vec<_>>())
    }

    pub fn bool(&self, key: &str) -> bool {
	    self.args.0.get(key).map(|vs| vs.first()

            .map(|v| v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("1")))
            .flatten().unwrap_or(false)
    }

    pub fn arg(&self, key: &str) -> Option<&str> {
        self.args.0.get(key).map(|vs| vs.first().map(|s| s.as_str())).flatten()
    }

    pub fn arg_or<'a>(&'a self, key: &str, def: &'a str) -> &'a str {
        self.arg(key).unwrap_or(def)
    }

    pub fn new() -> Self {
        let mut forward_args: Vec<_> = args().collect();
        let script_path = forward_args.remove(0);
        let mut paths: Vec<String> = vec![];
        let mut cli_args = CliArgs(Default::default());
        while forward_args.len() > 0 {
            let arg = forward_args.remove(0);
            match ArgType::parse(&arg) {
                ArgType::AssignExpr(left, right) => cli_args.set_value(left, right),
                ArgType::PrefixName => {
                    if let Some(next) = forward_args.get(0) {
                        if matches!(ArgType::parse(next), ArgType::Path) {
                            cli_args.set_value(arg, forward_args.remove(0));
                            continue;
                        }
                    }
                    cli_args.set_value(arg, "true".to_string());
                },
                ArgType::Path => paths.push(arg),
                ArgType::PassedSeparator => break,
            }
        };
        CliProtocol { meta: RpMeta::new((), None), script_path, forward_args, path: paths.join("/"), args: cli_args }
    }

    fn response(mut ctx: Context<CliProtocol>, err: Option<DceError>) {
        ctx.try_print_err(&err);
        if ctx.api().iter().any(|a| a.responsive) {
            if let Some(resp_sid) = ctx.resp_sid() {
                let prepend = format!("\n\nNew sid: {}", resp_sid);
                ctx.write_string(prepend);
            }
            let resp = ctx.clear_buffer();
            println!("{}", String::from_utf8_lossy(&resp));
        }
    }

    pub fn sync_handle(self, routed: DceResult<RouteMatch<'_, CliProtocol>>) {
        let mut ctx = Context::new(self, routed.as_ref().ok().map(|r| r.api));
        let err = match routed {
            Ok(routed) => routed.api.sync_handle(&mut ctx, routed).err(),
            err => err.err(),
        };
        Self::response(ctx, err);
    }

    pub async fn handle(self, routed: DceResult<RouteMatch<'_, CliProtocol>>) {
        let mut ctx = Context::new(self, routed.as_ref().ok().map(|r| r.api));
        let err = match routed {
            Ok(routed) => routed.api.handle(&mut ctx, routed).await.err(),
            err => err.err(),
        };
        Self::response(ctx, err);
    }
}

#[cfg_attr(not(feature = "sync"), async_trait)]
impl RoutableProtocol for CliProtocol {
    type Req = ();

    fn path(&self) -> &str {
        &self.path
    }

    fn sync_body(&mut self) -> DceResult<Bytes> {
        let mut buf = vec![];
        io::stdin().read_to_end(&mut buf)?;
        Ok(Bytes::copy_from_slice(&buf))
    }

    #[cfg(not(feature = "sync"))]
    async fn body(&mut self) -> DceResult<Bytes> {
        self.sync_body()
    }
}

#[allow(non_snake_case, non_upper_case_globals)]
pub static CliRouter: LazyLock<Arc<RwLock<Router<CliProtocol>>>> = LazyLock::new(|| Arc::new(RwLock::new(Router::<CliProtocol>::new())));

pub async fn cli_route(){
    let router = CliRouter.clone();
    let router = router.read().unwrap();
    let rp = CliProtocol::new();
    let routed = router.lookup(&rp);
    rp.handle(routed).await;
}