seems ok, but need to optimize for database write and read in the future

with cache etc
This commit is contained in:
open-trade 2020-05-15 09:42:29 +00:00
parent f3554b153d
commit 2424dcad69
2 changed files with 42 additions and 9 deletions

View File

@ -29,6 +29,17 @@ struct Peer {
last_reg_time: Instant,
}
impl Default for Peer {
fn default() -> Self {
Self {
socket_addr: "0.0.0.0:0".parse().unwrap(),
last_reg_time: Instant::now()
.checked_sub(std::time::Duration::from_secs(3600))
.unwrap(),
}
}
}
#[derive(Debug, Serialize, Deserialize, Default)]
struct PeerSerde {
#[serde(default)]
@ -45,13 +56,23 @@ impl PeerMap {
fn new() -> ResultType<Self> {
Ok(Self {
map: Default::default(),
db: super::SledAsync::new("./sled.db")?,
db: super::SledAsync::new("./sled.db", true)?,
})
}
#[inline]
fn insert(&mut self, key: String, peer: Peer) {
if self.map.write().unwrap().insert(key, peer).is_none() {}
let ip = peer.socket_addr.ip();
if self
.map
.write()
.unwrap()
.insert(key.clone(), peer)
.is_none()
{
let ip = ip.to_string();
self.db.insert(key, PeerSerde { ip });
}
}
#[inline]
@ -61,7 +82,7 @@ impl PeerMap {
return p;
} else {
if let Some(_) = self.db.get(key).await {
// to-do
return Some(Peer::default());
}
}
None

View File

@ -18,11 +18,15 @@ pub struct SledAsync {
}
impl SledAsync {
pub fn new(path: &str) -> ResultType<Self> {
Ok(Self {
pub fn new(path: &str, run: bool) -> ResultType<Self> {
let mut res = Self {
db: sled::open(path)?,
tx: None,
})
};
if run {
res.run();
}
Ok(res)
}
pub fn run(&mut self) -> std::thread::JoinHandle<()> {
@ -31,6 +35,7 @@ impl SledAsync {
let db = self.db.clone();
std::thread::spawn(move || {
Self::io_loop(db, rx);
log::debug!("Exit SledAsync loop");
})
}
@ -55,6 +60,13 @@ impl SledAsync {
}
}
pub fn _close(self, j: std::thread::JoinHandle<()>) {
if let Some(tx) = &self.tx {
allow_err!(tx.send(Action::Close));
}
allow_err!(j.join());
}
pub async fn get(&mut self, key: String) -> Option<sled::IVec> {
if let Some(tx) = &self.tx {
let (tx_once, mut rx) = mpsc::channel::<Option<sled::IVec>>(1);
@ -67,7 +79,7 @@ impl SledAsync {
}
#[inline]
pub fn deserialize<'a, T: serde::Deserialize<'a>>(v: &'a Option<sled::IVec>) -> Option<T> {
pub fn _deserialize<'a, T: serde::Deserialize<'a>>(v: &'a Option<sled::IVec>) -> Option<T> {
if let Some(v) = v {
if let Ok(v) = std::str::from_utf8(v) {
if let Ok(v) = serde_json::from_str::<T>(&v) {
@ -78,9 +90,9 @@ impl SledAsync {
None
}
pub fn insert<'a, T: serde::Serialize>(&mut self, key: String, v: &T) {
pub fn insert<T: serde::Serialize>(&mut self, key: String, v: T) {
if let Some(tx) = &self.tx {
if let Ok(v) = serde_json::to_vec(v) {
if let Ok(v) = serde_json::to_vec(&v) {
allow_err!(tx.send(Action::Insert((key, v))));
}
}