Skip to content

Commit

Permalink
allow multiple processes running at the same time
Browse files Browse the repository at this point in the history
  • Loading branch information
raine committed Aug 30, 2023
1 parent 5a53701 commit 3cfbba8
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions ghtool/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use eyre::Result;
use futures::Future;
use lazy_static::lazy_static;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use sled::Db;
use tracing::{debug, info};

lazy_static! {
Expand All @@ -15,11 +14,6 @@ lazy_static! {
info!(?path, "using cache path");
cache_path
};
pub static ref DB: Db = sled::Config::new()
.path(CACHE_DIR.as_str())
.use_compression(true)
.open()
.expect("failed to open database");
}

#[derive(Serialize, Deserialize)]
Expand All @@ -28,18 +22,21 @@ struct CacheValue<V> {
timestamp: SystemTime,
}

// The db needs to be opened in call to allow multiple processes
pub fn put<K, V>(key: K, value: V) -> Result<()>
where
K: AsRef<[u8]> + std::fmt::Debug,
V: Serialize,
{
let db = open_db()?;
let value = CacheValue {
value,
timestamp: SystemTime::now(),
};
let bytes = serde_json::to_vec(&value)?;
DB.insert(&key, bytes)?;
db.insert(&key, bytes)?;
debug!(?key, "cache key set");
db.flush()?;
Ok(())
}

Expand All @@ -48,7 +45,8 @@ where
K: AsRef<[u8]> + std::fmt::Debug,
V: DeserializeOwned,
{
let bytes = DB.get(&key)?;
let db = open_db()?;
let bytes = db.get(&key)?;
let value = match bytes {
Some(bytes) => {
debug!(?key, "found cached key");
Expand Down Expand Up @@ -78,3 +76,11 @@ where
}
}
}

fn open_db() -> Result<sled::Db> {
let db = sled::Config::new()
.path(CACHE_DIR.as_str())
.use_compression(true)
.open()?;
Ok(db)
}

0 comments on commit 3cfbba8

Please sign in to comment.