Skip to content
This repository has been archived by the owner on May 2, 2024. It is now read-only.

Commit

Permalink
chore: added sqlite to store peer info
Browse files Browse the repository at this point in the history
  • Loading branch information
Lilit0x committed Aug 7, 2023
1 parent c7a008b commit 711c77d
Show file tree
Hide file tree
Showing 6 changed files with 274 additions and 6 deletions.
85 changes: 81 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions share/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ request_response = {version = "0.25.0", package = "libp2p-request-response", fea
directories-next = "2.0.0"
tracing-appender = "0.2.2"
serde_yaml = "0.9.24"
rusqlite = { version = "0.29.0", features = ["bundled"] }
time = "0.3.25"

[dev-dependencies]
assert_fs = "1.0.13"
Expand Down
81 changes: 81 additions & 0 deletions share/src/database/mod.rs
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)]

Check warning on line 17 in share/src/database/mod.rs

View check run for this annotation

Codecov / codecov/patch

share/src/database/mod.rs#L17

Added line #L17 was not covered by tests
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(())
}

Check warning on line 65 in share/src/database/mod.rs

View check run for this annotation

Codecov / codecov/patch

share/src/database/mod.rs#L56-L65

Added lines #L56 - L65 were not covered by tests
}

#[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(())
}
}
87 changes: 87 additions & 0 deletions share/src/database/peer.rs
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)]

Check warning on line 12 in share/src/database/peer.rs

View check run for this annotation

Codecov / codecov/patch

share/src/database/peer.rs#L12

Added line #L12 was not covered by tests
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");

Check warning on line 23 in share/src/database/peer.rs

View check run for this annotation

Codecov / codecov/patch

share/src/database/peer.rs#L22-L23

Added lines #L22 - L23 were not covered by tests

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)?,

Check warning on line 30 in share/src/database/peer.rs

View check run for this annotation

Codecov / codecov/patch

share/src/database/peer.rs#L25-L30

Added lines #L25 - L30 were not covered by tests
};
Ok(peer)
}

Check warning on line 33 in share/src/database/peer.rs

View check run for this annotation

Codecov / codecov/patch

share/src/database/peer.rs#L32-L33

Added lines #L32 - L33 were not covered by tests

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,
}
}

Check warning on line 50 in share/src/database/peer.rs

View check run for this annotation

Codecov / codecov/patch

share/src/database/peer.rs#L39-L50

Added lines #L39 - L50 were not covered by tests
}

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)
}

Check warning on line 60 in share/src/database/peer.rs

View check run for this annotation

Codecov / codecov/patch

share/src/database/peer.rs#L54-L60

Added lines #L54 - L60 were not covered by tests

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(())
}

Check warning on line 70 in share/src/database/peer.rs

View check run for this annotation

Codecov / codecov/patch

share/src/database/peer.rs#L62-L70

Added lines #L62 - L70 were not covered by tests

pub fn get_peer(name: String, store: &Store) -> Result<ScsPeer> {
let conn = store.get_conn_handle();

Check warning on line 73 in share/src/database/peer.rs

View check run for this annotation

Codecov / codecov/patch

share/src/database/peer.rs#L72-L73

Added lines #L72 - L73 were not covered by tests

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}"))

Check warning on line 82 in share/src/database/peer.rs

View check run for this annotation

Codecov / codecov/patch

share/src/database/peer.rs#L75-L82

Added lines #L75 - L82 were not covered by tests
} else {
Ok(peers.first().unwrap().clone())

Check warning on line 84 in share/src/database/peer.rs

View check run for this annotation

Codecov / codecov/patch

share/src/database/peer.rs#L84

Added line #L84 was not covered by tests
}
}

Check warning on line 86 in share/src/database/peer.rs

View check run for this annotation

Codecov / codecov/patch

share/src/database/peer.rs#L86

Added line #L86 was not covered by tests
}
11 changes: 10 additions & 1 deletion share/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use clap::Parser;
use config::Config;
use database::Store;
use libp2p::PeerId;
use network::punch;
use std::{process::exit, str::FromStr};
use tracing::error;

mod config;
mod database;
mod handlers;
mod item;
mod logger;
Expand Down Expand Up @@ -81,9 +83,16 @@ async fn main() {
};

logger::log(&config).unwrap();
let store = match Store::initialize() {
Ok(store) => store,
Err(err) => {
error!("{:#?}", err.to_string());
exit(1)

Check warning on line 90 in share/src/main.rs

View check run for this annotation

Codecov / codecov/patch

share/src/main.rs#L86-L90

Added lines #L86 - L90 were not covered by tests
}
};

let code = {
match punch(mode, remote_peer_id, config) {
match punch(mode, remote_peer_id, config, store) {

Check warning on line 95 in share/src/main.rs

View check run for this annotation

Codecov / codecov/patch

share/src/main.rs#L95

Added line #L95 was not covered by tests
Ok(_) => 1,
Err(err) => {
error!("{:#?}", err.to_string());
Expand Down
Loading

0 comments on commit 711c77d

Please sign in to comment.