This repository has been archived by the owner on May 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: added sqlite to store peer info
- Loading branch information
Showing
6 changed files
with
274 additions
and
6 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
use std::{ | ||
fs, | ||
sync::{Arc, Mutex, MutexGuard}, | ||
}; | ||
|
||
use anyhow::{Context, Result}; | ||
use libp2p::{Multiaddr, PeerId, Swarm}; | ||
use rusqlite::Connection; | ||
use tracing::debug; | ||
|
||
use crate::network::Behaviour; | ||
|
||
use self::peer::ScsPeer; | ||
|
||
pub mod peer; | ||
|
||
#[derive(Debug)] | ||
pub struct Store { | ||
// db_path: PathBuf, | ||
conn: Arc<Mutex<Connection>>, | ||
} | ||
|
||
impl Store { | ||
pub fn initialize() -> Result<Store> { | ||
debug!("Initializing Database Connection"); | ||
let dirs = | ||
directories_next::ProjectDirs::from("com", "onboardbase", "secureshare").unwrap(); | ||
let path = dirs.data_local_dir(); | ||
fs::create_dir_all(path).context("Failed to create default directory")?; | ||
let path = path.join("scs.db3"); | ||
let conn = Connection::open(path)?; | ||
|
||
debug!("Preparing to execute schema"); | ||
conn.execute( | ||
"CREATE TABLE IF NOT EXISTS peer ( | ||
id INTEGER PRIMARY KEY, | ||
name TEXT NOT NULL UNIQUE, | ||
addrs BLOB, | ||
peer_id TEXT NOT NULL UNIQUE, | ||
last_seen TEXT | ||
)", | ||
(), // empty list of parameters. | ||
)?; | ||
debug!("Executed schema creation for peer"); | ||
|
||
let settings = Store { | ||
conn: Arc::new(Mutex::new(conn)), | ||
}; | ||
Ok(settings) | ||
} | ||
|
||
pub fn get_conn_handle(&self) -> MutexGuard<'_, Connection> { | ||
self.conn.lock().unwrap() | ||
} | ||
|
||
pub fn store_peer(&self, swarm: &mut Swarm<Behaviour>, peer_id: PeerId) -> Result<()> { | ||
debug!("Initiating Peer Storage"); | ||
let addrs = swarm.external_addresses().collect::<Vec<_>>(); | ||
//FIXME chnage this to the connector address | ||
let addr = <&Multiaddr>::clone(addrs.first().unwrap()); | ||
let name = "testing_t".to_string(); | ||
let peer = ScsPeer::from((addr, name, peer_id)); | ||
peer.save(self)?; | ||
Ok(()) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use anyhow::Result; | ||
|
||
use super::Store; | ||
|
||
#[test] | ||
fn initialize_db() -> Result<()> { | ||
let settings = Store::initialize()?; | ||
let conn = settings.get_conn_handle(); | ||
assert!(conn.is_autocommit()); | ||
Ok(()) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
#![allow(dead_code)] | ||
|
||
use anyhow::{anyhow, Result}; | ||
use libp2p::{Multiaddr, PeerId}; | ||
use rusqlite::{named_params, Row}; | ||
use tracing::debug; | ||
|
||
use time::OffsetDateTime; | ||
|
||
use super::Store; | ||
|
||
#[derive(Debug, Clone)] | ||
pub struct ScsPeer { | ||
addrs: String, | ||
name: String, | ||
last_seen: String, | ||
peer_id: String, | ||
id: Option<i32>, | ||
} | ||
|
||
impl TryFrom<&Row<'_>> for ScsPeer { | ||
fn try_from(row: &Row<'_>) -> Result<Self> { | ||
debug!("Creating Peer from Row"); | ||
|
||
let peer = ScsPeer { | ||
id: row.get(0)?, | ||
name: row.get(1)?, | ||
addrs: row.get(2)?, | ||
peer_id: row.get(3)?, | ||
last_seen: row.get(4)?, | ||
}; | ||
Ok(peer) | ||
} | ||
|
||
type Error = anyhow::Error; | ||
} | ||
|
||
impl From<(&Multiaddr, String, PeerId)> for ScsPeer { | ||
fn from(value: (&Multiaddr, String, PeerId)) -> Self { | ||
debug!("Creating Peer from tuple"); | ||
let (addr, name, peer_id) = value; | ||
let local = OffsetDateTime::now_utc(); | ||
ScsPeer { | ||
addrs: addr.to_string(), | ||
name, | ||
last_seen: local.to_string(), | ||
peer_id: peer_id.to_string(), | ||
id: None, | ||
} | ||
} | ||
} | ||
|
||
impl ScsPeer { | ||
pub fn fetch_all_peers(store: &Store) -> Result<Vec<ScsPeer>> { | ||
let conn = store.get_conn_handle(); | ||
let mut stmt = conn.prepare("SELECT id, name, addrs, last_seen FROM peer")?; | ||
let peer_iter = stmt.query_map([], |row| Ok(ScsPeer::try_from(row).unwrap()))?; | ||
let peers = peer_iter.filter_map(|peer| peer.ok()).collect::<Vec<_>>(); | ||
Ok(peers) | ||
} | ||
|
||
pub fn save(&self, store: &Store) -> Result<()> { | ||
debug!("Saving Peer"); | ||
let conn = store.get_conn_handle(); | ||
conn.execute( | ||
"INSERT INTO peer (name, addrs, last_seen, peer_id) VALUES (?1, ?2, ?3, ?4)", | ||
(&self.name, &self.addrs, &self.last_seen, &self.peer_id), | ||
)?; | ||
Ok(()) | ||
} | ||
|
||
pub fn get_peer(name: String, store: &Store) -> Result<ScsPeer> { | ||
let conn = store.get_conn_handle(); | ||
|
||
let mut statement = | ||
conn.prepare("SELECT id, name, addrs, last_seen FROM peer WHERE name = :name")?; | ||
let peer_iter = statement.query_map(named_params! { ":name": name }, |row| { | ||
Ok(ScsPeer::try_from(row).unwrap()) | ||
})?; | ||
let peers = peer_iter.filter_map(|peer| peer.ok()).collect::<Vec<_>>(); | ||
if peers.is_empty() { | ||
Err(anyhow!("Cannot find peer with name: {name}")) | ||
} else { | ||
Ok(peers.first().unwrap().clone()) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.