rustdesk-server/src/sled_async.rs

102 lines
2.7 KiB
Rust
Raw Normal View History

2020-05-15 03:16:46 +08:00
use hbb_common::{
allow_err, log,
tokio::{self, sync::mpsc},
ResultType,
};
2021-03-19 11:32:28 +08:00
use rocksdb::DB;
2020-05-15 03:16:46 +08:00
#[derive(Debug)]
enum Action {
Insert((String, Vec<u8>)),
2021-03-19 11:32:28 +08:00
Get((String, mpsc::Sender<Option<Vec<u8>>>)),
2020-07-09 02:16:59 +08:00
_Close,
2020-05-15 03:16:46 +08:00
}
#[derive(Clone)]
pub struct SledAsync {
tx: Option<mpsc::UnboundedSender<Action>>,
2021-03-19 11:32:28 +08:00
path: String,
2020-05-15 03:16:46 +08:00
}
impl SledAsync {
pub fn new(path: &str, run: bool) -> ResultType<Self> {
let mut res = Self {
2020-05-15 03:16:46 +08:00
tx: None,
2021-03-19 11:32:28 +08:00
path: path.to_owned(),
};
if run {
2021-03-19 11:32:28 +08:00
res.run()?;
}
Ok(res)
2020-05-15 03:16:46 +08:00
}
2021-03-19 11:32:28 +08:00
pub fn run(&mut self) -> ResultType<std::thread::JoinHandle<()>> {
2020-05-15 03:16:46 +08:00
let (tx, rx) = mpsc::unbounded_channel::<Action>();
self.tx = Some(tx);
2021-03-19 11:32:28 +08:00
let db = DB::open_default(&self.path)?;
Ok(std::thread::spawn(move || {
2020-05-15 03:16:46 +08:00
Self::io_loop(db, rx);
log::debug!("Exit SledAsync loop");
2021-03-19 11:32:28 +08:00
}))
2020-05-15 03:16:46 +08:00
}
#[tokio::main(basic_scheduler)]
2021-03-19 11:32:28 +08:00
async fn io_loop(db: DB, rx: mpsc::UnboundedReceiver<Action>) {
2020-05-15 03:16:46 +08:00
let mut rx = rx;
while let Some(x) = rx.recv().await {
match x {
Action::Insert((key, value)) => {
2021-03-19 11:32:28 +08:00
allow_err!(db.put(&key, &value));
2020-05-15 03:16:46 +08:00
}
Action::Get((key, sender)) => {
let mut sender = sender;
allow_err!(
sender
.send(if let Ok(v) = db.get(key) { v } else { None })
.await
);
}
2020-07-09 02:16:59 +08:00
Action::_Close => break,
2020-05-15 03:16:46 +08:00
}
}
}
pub fn _close(self, j: std::thread::JoinHandle<()>) {
if let Some(tx) = &self.tx {
2020-07-09 02:16:59 +08:00
allow_err!(tx.send(Action::_Close));
}
allow_err!(j.join());
}
2021-03-19 11:32:28 +08:00
pub async fn get(&mut self, key: String) -> Option<Vec<u8>> {
2020-05-15 03:16:46 +08:00
if let Some(tx) = &self.tx {
2021-03-19 11:32:28 +08:00
let (tx_once, mut rx) = mpsc::channel::<Option<Vec<u8>>>(1);
2020-05-15 03:16:46 +08:00
allow_err!(tx.send(Action::Get((key, tx_once))));
if let Some(v) = rx.recv().await {
return v;
}
}
None
}
#[inline]
2021-03-19 11:32:28 +08:00
pub fn deserialize<'a, T: serde::Deserialize<'a>>(v: &'a Option<Vec<u8>>) -> Option<T> {
2020-05-15 03:16:46 +08:00
if let Some(v) = v {
if let Ok(v) = std::str::from_utf8(v) {
if let Ok(v) = serde_json::from_str::<T>(&v) {
return Some(v);
}
}
}
None
}
pub fn insert<T: serde::Serialize>(&mut self, key: String, v: T) {
2020-05-15 03:16:46 +08:00
if let Some(tx) = &self.tx {
if let Ok(v) = serde_json::to_vec(&v) {
2020-05-15 03:16:46 +08:00
allow_err!(tx.send(Action::Insert((key, v))));
}
}
}
}