use std::collections::BTreeMap;
use std::sync::Arc;
use async_trait::async_trait;
use crate::error::Result;
use crate::url::Url;
#[derive(Debug, Clone, Default)]
pub struct RpcContext {
pub attachments: BTreeMap<String, String>,
}
#[derive(Debug, Clone)]
pub struct Request {
pub service_name: String,
pub method_name: String,
pub version: String,
pub args: Vec<Vec<u8>>, pub context: RpcContext,
}
impl Request {
pub fn new(method_name: String) -> Self {
Self {
service_name: String::new(),
method_name,
version: "0.0.0".to_string(),
args: Vec::new(),
context: RpcContext::default(),
}
}
}
#[derive(Debug, Clone)]
pub struct Response {
pub value: Option<Vec<u8>>, pub exception: Option<String>,
pub context: RpcContext,
}
impl Response {
pub fn ok(value: Vec<u8>) -> Self {
Self {
value: Some(value),
exception: None,
context: RpcContext::default(),
}
}
pub fn error(msg: String) -> Self {
Self {
value: None,
exception: Some(msg),
context: RpcContext::default(),
}
}
}
#[async_trait]
pub trait Invoker: Send + Sync {
async fn invoke(&self, req: Request) -> Result<Response>;
fn url(&self) -> &Url;
}
#[async_trait]
impl<T: Invoker + ?Sized> Invoker for Arc<T> {
async fn invoke(&self, req: Request) -> Result<Response> {
(**self).invoke(req).await
}
fn url(&self) -> &Url {
(**self).url()
}
}