use std::collections::HashMap;
use crate::error::RpcStatusCode;
pub type Metadata = HashMap<String, String>;
#[derive(Debug, Clone)]
pub struct RpcRequest {
pub method: String,
pub metadata: Metadata,
pub body: Vec<u8>,
}
#[derive(Debug, Clone)]
pub struct RpcResponse {
pub status: RpcStatus,
pub metadata: Metadata,
pub body: Vec<u8>,
}
#[derive(Debug, Clone)]
pub struct RpcStatus {
pub code: RpcStatusCode,
pub message: String,
}
impl RpcRequest {
pub fn new(method: impl Into<String>, body: Vec<u8>) -> Self {
Self {
method: method.into(),
metadata: Metadata::new(),
body,
}
}
pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.metadata.insert(key.into(), value.into());
self
}
pub fn service_name(&self) -> Option<&str> {
self.method.split('/').next()
}
pub fn method_name(&self) -> Option<&str> {
self.method.split('/').nth(1)
}
}
impl RpcResponse {
pub fn ok(body: Vec<u8>) -> Self {
Self {
status: RpcStatus {
code: RpcStatusCode::Ok,
message: String::new(),
},
metadata: Metadata::new(),
body,
}
}
pub fn error(code: RpcStatusCode, message: impl Into<String>) -> Self {
Self {
status: RpcStatus {
code,
message: message.into(),
},
metadata: Metadata::new(),
body: Vec::new(),
}
}
pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.metadata.insert(key.into(), value.into());
self
}
}
impl RpcStatus {
pub fn ok() -> Self {
Self {
code: RpcStatusCode::Ok,
message: String::new(),
}
}
pub fn is_ok(&self) -> bool {
self.code == RpcStatusCode::Ok
}
}