Skip to main content

rubbo_core/
rpc.rs

1use std::collections::BTreeMap;
2use std::sync::Arc;
3use async_trait::async_trait;
4use crate::error::Result;
5use crate::url::Url;
6
7/// RpcContext passing through the invocation chain
8#[derive(Debug, Clone, Default)]
9pub struct RpcContext {
10    pub attachments: BTreeMap<String, String>,
11}
12
13/// Generic RPC Request
14#[derive(Debug, Clone)]
15pub struct Request {
16    pub service_name: String,
17    pub method_name: String,
18    pub version: String,
19    pub args: Vec<Vec<u8>>, // Serialized arguments
20    pub context: RpcContext,
21}
22
23impl Request {
24    pub fn new(method_name: String) -> Self {
25        Self {
26            service_name: String::new(),
27            method_name,
28            version: "0.0.0".to_string(),
29            args: Vec::new(),
30            context: RpcContext::default(),
31        }
32    }
33}
34
35/// Generic RPC Response
36#[derive(Debug, Clone)]
37pub struct Response {
38    pub value: Option<Vec<u8>>, // Serialized return value
39    pub exception: Option<String>,
40    pub context: RpcContext,
41}
42
43impl Response {
44    pub fn ok(value: Vec<u8>) -> Self {
45        Self {
46            value: Some(value),
47            exception: None,
48            context: RpcContext::default(),
49        }
50    }
51
52    pub fn error(msg: String) -> Self {
53        Self {
54            value: None,
55            exception: Some(msg),
56            context: RpcContext::default(),
57        }
58    }
59}
60
61/// Invoker trait - the core concept in Dubbo
62#[async_trait]
63pub trait Invoker: Send + Sync {
64    async fn invoke(&self, req: Request) -> Result<Response>;
65    fn url(&self) -> &Url;
66}
67
68#[async_trait]
69impl<T: Invoker + ?Sized> Invoker for Arc<T> {
70    async fn invoke(&self, req: Request) -> Result<Response> {
71        (**self).invoke(req).await
72    }
73    fn url(&self) -> &Url {
74        (**self).url()
75    }
76}