krpc_common/
lib.rs

1use std::{
2    fmt::{self, Display, Formatter},
3    net::IpAddr,
4};
5
6use serde::{Deserialize, Serialize};
7use tracing_subscriber::fmt::writer::MakeWriterExt;
8
9pub type Error = Box<dyn std::error::Error + Send + Sync>;
10pub type Result<T> = std::result::Result<T, Error>;
11pub type Response<T> = std::result::Result<T, String>;
12pub type KrpcFuture<T> = std::pin::Pin<Box<dyn std::future::Future<Output = T> + Send>>;
13
14pub mod date_util;
15pub mod url_util;
16
17#[derive(Serialize, Deserialize, Debug)]
18pub enum RpcError {
19    Null,
20    Client(String),
21    Server(String),
22    Method(String),
23}
24
25unsafe impl Send for RpcError {}
26unsafe impl Sync for RpcError {}
27
28impl Display for RpcError {
29    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
30        match self {
31            RpcError::Null => write!(f, "Bad value"),
32            RpcError::Client(msg) => write!(f, "RpcError::Client {}", msg),
33            RpcError::Server(msg) => write!(f, "RpcError::Server {}", msg),
34            RpcError::Method(msg) => write!(f, "RpcError::Method {}", msg),
35        }
36    }
37}
38
39impl std::error::Error for RpcError {}
40
41#[derive(Debug)]
42pub struct KrpcMsg {
43    pub unique_identifier: String,
44    pub version: Option<String>,
45    pub class_name: String,
46    pub method_name: String,
47    pub req: Vec<String>,
48    pub res: core::result::Result<String, RpcError>,
49}
50
51impl KrpcMsg {
52    pub fn new_empty() -> KrpcMsg {
53        return KrpcMsg {
54            unique_identifier: "".to_string(),
55            version: None,
56            class_name: "".to_string(),
57            method_name: "".to_string(),
58            req: vec![],
59            res: Err(RpcError::Null),
60        };
61    }
62
63    pub fn new(
64        unique_identifier: String,
65        version: Option<String>,
66        class_name: String,
67        method_name: String,
68        req: Vec<String>,
69        res: core::result::Result<String, RpcError>,
70    ) -> KrpcMsg {
71        return KrpcMsg {
72            unique_identifier,
73            version,
74            class_name,
75            method_name,
76            req,
77            res,
78        };
79    }
80}
81
82pub trait RpcServer: Send + Sync {
83    fn invoke(&self, msg: KrpcMsg) -> KrpcFuture<KrpcMsg>;
84    fn get_info(&self) -> (&str, &str, Option<&str>, Vec<String>);
85}
86
87pub fn init_log() {
88    let stdout = std::io::stdout.with_max_level(tracing::Level::DEBUG);
89    tracing_subscriber::fmt()
90        .with_writer(stdout)
91        .with_line_number(true)
92        .with_thread_ids(true)
93        .init();
94}
95
96pub fn get_uuid() -> String {
97    uuid::Uuid::new_v4().to_string()
98}
99
100pub fn get_network_ip() -> std::result::Result<IpAddr, Box<dyn std::error::Error>> {
101    let socket = std::net::UdpSocket::bind("0.0.0.0:0")?;
102    socket.connect("8.8.8.8:80")?;
103    let local_ip = socket.local_addr()?.ip();
104    Ok(local_ip)
105}
106
107pub fn get_ip() -> String {
108    match get_network_ip() {
109        Ok(ok) => ok.to_string(),
110        Err(_err) => "127.0.0.1".to_string(),
111    }
112}