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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
use rmp_serde; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::Value; use std::collections::HashMap; use std::convert::TryInto; use log::{debug, error}; fn se_checksum<S>(checksum: &Option<[u8; 32]>, s: S) -> Result<S::Ok, S::Error> where S: Serializer, { match checksum { Some(v) => s.serialize_str(hex::encode(v).as_str()), None => s.serialize_none(), } } fn de_checksum<'de, D>(deserializer: D) -> Result<Option<[u8; 32]>, D::Error> where D: Deserializer<'de>, { match Value::deserialize(deserializer) { Ok(v) => match v { Value::String(s) => match hex::decode(s) { Ok(c) => { let result: [u8; 32] = match c.try_into() { Ok(value) => value, Err(_) => return Err(serde::de::Error::custom("sha256 length error")), }; Ok(Some(result)) } Err(e) => Err(serde::de::Error::custom(e)), }, Value::Null => Ok(None), _ => Err(serde::de::Error::custom("sha256 should be string")), }, Err(e) => Err(e), } } #[derive(Debug, Serialize, Deserialize)] pub struct KeyExplained { pub value: Value, pub schema: Option<String>, pub len: Option<u64>, #[serde(rename(serialize = "type", deserialize = "type"))] pub tp: String, pub mtime: u64, pub size: u64, #[serde(serialize_with = "se_checksum", deserialize_with = "de_checksum")] pub sha256: Option<[u8; 32]>, pub stime: Option<u64>, pub file: String, } fn default_auto_bak() -> u64 { 0 } #[derive(Debug, Serialize, Deserialize)] pub struct DBInfo { pub repair_recommended: bool, pub cached_keys: usize, pub cache_size: usize, #[serde(default = "default_auto_bak")] pub auto_bak: u64, pub auto_flush: bool, pub path: String, pub lock_path: String, pub server: (String, String), pub fmt: String, pub checksums: bool, pub created: u64, pub version: u8, } #[derive(Eq, PartialEq, Copy, Clone)] pub enum ErrorKind { IOError, DataError, TimeoutError, KeyNotFound, FieldNotFound, SchemaValidationError, UnsupportedFormat, UnsupportedVersion, NotOpened, Busy, NotInitialized, RequestError, ProtocolError, MethodNotFound, InvalidParameter, Other, Eof, } impl ErrorKind { pub fn to_string(&self) -> String { use ErrorKind::*; (match self { IOError => "I/O Error", DataError => "Data error", TimeoutError => "Timeout error", KeyNotFound => "Key not found", FieldNotFound => "Field not found", SchemaValidationError => "Schema validation error", UnsupportedFormat => "Unsupported format", UnsupportedVersion => "Unsupported version", NotOpened => "Not opened", Busy => "Database is busy", NotInitialized => "Not initialized", RequestError => "Request error", ProtocolError => "Protocol error", MethodNotFound => "Method not found", InvalidParameter => "Invalid parameter", Eof => "EOF", Other => "Error", }) .to_owned() } } fn de_errorkind<'de, D>(deserializer: D) -> Result<ErrorKind, D::Error> where D: Deserializer<'de>, { use ErrorKind::*; Ok(match i32::deserialize(deserializer) { Ok(n) => match n { -32001 => KeyNotFound, -32002 => DataError, -32003 => SchemaValidationError, -32004 => IOError, -32601 => MethodNotFound, -32602 => InvalidParameter, -32681 => FieldNotFound, _ => Other, }, Err(_) => Other, }) } impl Serialize for ErrorKind { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { use ErrorKind::*; let code = match self { KeyNotFound => -32001, DataError => -32002, SchemaValidationError => -32003, IOError => -32004, MethodNotFound => -32601, InvalidParameter => -32602, FieldNotFound => -32681, _ => -32000, }; serializer.serialize_i32(code) } } impl std::fmt::Display for ErrorKind { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.to_string()) } } impl std::fmt::Debug for ErrorKind { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.to_string()) } } #[derive(Debug, Serialize, Deserialize)] pub struct Error { #[serde( rename(serialize = "code", deserialize = "code"), deserialize_with = "de_errorkind" )] error_kind: ErrorKind, message: String, } impl Error { pub fn new<E: std::fmt::Display>(kind: ErrorKind, error: E) -> Self { if kind == ErrorKind::KeyNotFound { debug!("{} {}", kind, error); } else { error!("error {} {}", kind, error); } Self { error_kind: kind, message: format!("{}", error), } } pub fn kind(&self) -> ErrorKind { self.error_kind } pub fn to_string(&self) -> String { self.error_kind.to_string() + ": " + self.message.as_str() } pub fn get_message(&self) -> String { self.message.clone() } pub fn err_invalid_parameter() -> Self { Self { error_kind: ErrorKind::InvalidParameter, message: "Invalid method parameter".to_owned(), } } pub fn err_method_not_found() -> Self { Self { error_kind: ErrorKind::MethodNotFound, message: "Method not found".to_owned(), } } } impl std::error::Error for Error {} impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}: {}", self.error_kind, self.message) } } #[derive(Serialize, Deserialize, Debug)] pub struct JSONRpcRequest { jsonrpc: String, pub id: Value, pub method: String, pub params: HashMap<String, serde_json::Value>, } impl JSONRpcRequest { pub fn new(id: u64, method: &str) -> Self { Self { id: Value::from(id), jsonrpc: "2.0".to_owned(), method: method.to_owned(), params: HashMap::new(), } } pub fn set_param(&mut self, name: &str, value: Value) { self.params.insert(name.to_owned(), value); } pub fn pack(&self) -> Result<Vec<u8>, Error> { match rmp_serde::to_vec_named(&self) { Ok(v) => Ok(v), Err(e) => Err(Error::new(ErrorKind::RequestError, e)), } } pub fn respond<T: Serialize>(&self, result: T) -> JSONRpcResponse<T> { JSONRpcResponse { jsonrpc: self.jsonrpc.to_owned(), id: self.id.clone(), result: Some(result), error: None, } } pub fn respond_ok(&self) -> JSONRpcResponse<Value> { return self.respond(serde_json::json!({"ok": true })); } pub fn is_valid(&self) -> bool { return self.jsonrpc == "2.0"; } pub fn error(&self, err: Error) -> JSONRpcResponse<Value> { JSONRpcResponse { jsonrpc: self.jsonrpc.to_owned(), id: self.id.clone(), result: None, error: Some(err), } } pub fn params_valid(&self, params: Vec<&str>) -> bool { let keys = self.params.keys(); for k in keys { if !params.contains(&k.as_str()) { return false; } } for k in params { if !self.params.contains_key(k) { return false; } } true } } #[derive(Serialize, Deserialize, Debug)] pub struct JSONRpcResponse<T: Serialize> { jsonrpc: String, pub id: Value, #[serde(skip_serializing_if = "Option::is_none")] pub result: Option<T>, #[serde(skip_serializing_if = "Option::is_none")] pub error: Option<Error>, } #[derive(Serialize)] pub struct JSONRpcError { code: i16, message: String, }