1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
|
use std::{collections::HashMap, sync::Arc};
use log::{debug, error, warn};
use smol::lock::RwLock;
use karyon_core::{
async_util::{TaskGroup, TaskResult},
Executor,
};
use karyon_net::{Conn, Listener, ToListener};
use crate::{
codec::{Codec, CodecConfig},
message,
service::RPCService,
Endpoint, Error, Result, JSONRPC_VERSION,
};
pub const INVALID_REQUEST_ERROR_MSG: &str = "Invalid request";
pub const FAILED_TO_PARSE_ERROR_MSG: &str = "Failed to parse";
pub const METHOD_NOT_FOUND_ERROR_MSG: &str = "Method not found";
pub const INTERNAL_ERROR_MSG: &str = "Internal error";
fn pack_err_res(code: i32, msg: &str, id: Option<serde_json::Value>) -> message::Response {
let err = message::Error {
code,
message: msg.to_string(),
data: None,
};
message::Response {
jsonrpc: JSONRPC_VERSION.to_string(),
error: Some(err),
result: None,
id,
}
}
/// RPC server config
#[derive(Default)]
pub struct ServerConfig {
codec_config: CodecConfig,
}
/// Represents an RPC server
pub struct Server<'a> {
listener: Listener,
services: RwLock<HashMap<String, Box<dyn RPCService + 'a>>>,
task_group: TaskGroup<'a>,
config: ServerConfig,
}
impl<'a> Server<'a> {
/// Creates a new RPC server by passing a listener. It supports Tcp, Unix, and Tls.
pub fn new<T: ToListener>(listener: T, config: ServerConfig, ex: Executor<'a>) -> Arc<Self> {
Arc::new(Self {
listener: listener.to_listener(),
services: RwLock::new(HashMap::new()),
task_group: TaskGroup::new(ex),
config,
})
}
/// Returns the local endpoint.
pub fn local_endpoint(&self) -> Result<Endpoint> {
self.listener.local_endpoint().map_err(Error::KaryonNet)
}
/// Starts the RPC server
pub async fn start(self: Arc<Self>) -> Result<()> {
loop {
let conn = self.listener.accept().await?;
if let Err(err) = self.handle_conn(conn).await {
error!("Failed to handle a new conn: {err}")
}
}
}
/// Attach a new service to the RPC server
pub async fn attach_service(&self, service: impl RPCService + 'a) {
self.services
.write()
.await
.insert(service.name(), Box::new(service));
}
/// Shuts down the RPC server
pub async fn shutdown(&self) {
self.task_group.cancel().await;
}
/// Handles a new connection
async fn handle_conn(self: &Arc<Self>, conn: Conn) -> Result<()> {
let endpoint = conn.peer_endpoint()?;
debug!("Handle a new connection {endpoint}");
let on_failure = |result: TaskResult<Result<()>>| async move {
if let TaskResult::Completed(Err(err)) = result {
error!("Connection {} dropped: {}", endpoint, err);
} else {
warn!("Connection {} dropped", endpoint);
}
};
let codec = Codec::new(conn, self.config.codec_config.clone());
let selfc = self.clone();
self.task_group.spawn(
async move {
loop {
let mut buffer = vec![];
codec.read_until(&mut buffer).await?;
let response = selfc.handle_request(&buffer).await;
let mut payload = serde_json::to_vec(&response)?;
payload.push(b'\n');
codec.write_all(&payload).await?;
debug!("--> {response}");
}
},
on_failure,
);
Ok(())
}
/// Handles a request
async fn handle_request(&self, buffer: &[u8]) -> message::Response {
let rpc_msg = match serde_json::from_slice::<message::Request>(buffer) {
Ok(m) => m,
Err(_) => {
return pack_err_res(message::PARSE_ERROR_CODE, FAILED_TO_PARSE_ERROR_MSG, None);
}
};
debug!("<-- {rpc_msg}");
let srvc_method: Vec<&str> = rpc_msg.method.split('.').collect();
if srvc_method.len() != 2 {
return pack_err_res(
message::INVALID_REQUEST_ERROR_CODE,
INVALID_REQUEST_ERROR_MSG,
Some(rpc_msg.id),
);
}
let srvc_name = srvc_method[0];
let method_name = srvc_method[1];
let services = self.services.read().await;
let service = match services.get(srvc_name) {
Some(s) => s,
None => {
return pack_err_res(
message::METHOD_NOT_FOUND_ERROR_CODE,
METHOD_NOT_FOUND_ERROR_MSG,
Some(rpc_msg.id),
);
}
};
let method = match service.get_method(method_name) {
Some(m) => m,
None => {
return pack_err_res(
message::METHOD_NOT_FOUND_ERROR_CODE,
METHOD_NOT_FOUND_ERROR_MSG,
Some(rpc_msg.id),
);
}
};
let result = match method(rpc_msg.params.clone()).await {
Ok(res) => res,
Err(Error::ParseJSON(_)) => {
return pack_err_res(
message::PARSE_ERROR_CODE,
FAILED_TO_PARSE_ERROR_MSG,
Some(rpc_msg.id),
);
}
Err(Error::InvalidParams(msg)) => {
return pack_err_res(message::INVALID_PARAMS_ERROR_CODE, msg, Some(rpc_msg.id));
}
Err(Error::InvalidRequest(msg)) => {
return pack_err_res(message::INVALID_REQUEST_ERROR_CODE, msg, Some(rpc_msg.id));
}
Err(Error::RPCMethodError(code, msg)) => {
return pack_err_res(code, msg, Some(rpc_msg.id));
}
Err(_) => {
return pack_err_res(
message::INTERNAL_ERROR_CODE,
INTERNAL_ERROR_MSG,
Some(rpc_msg.id),
);
}
};
message::Response {
jsonrpc: JSONRPC_VERSION.to_string(),
error: None,
result: Some(result),
id: Some(rpc_msg.id),
}
}
}
|