mirror of
https://seed.radicle.dev/rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5.git
synced 2026-11-28 21:50:26 +08:00
radicle: Consolidate databases
Instead of having a routing database, and an addresses database, consolidate that in a single database called `node.db`. We also simplify database access, by providing a single type for opening the database, and use traits to access the various functions. We create a new `seed::Store` that has seed-related methods split out of the `address::Store`. Note that tracking is still in its own database currently, as it isn't ephemeral state. This makes it easy to delete the new `node.db` without risk of losing any important information. To avoid renaming all database methods, we create a `Stores` wrapper that allows us to access routing, addresses, seeds etc. without type ambiguity. This is a breaking change and requires `addresses.db` and `routing.db` to be deleted.
This commit is contained in:
+16
-25
@@ -19,7 +19,6 @@ use radicle::node;
|
||||
use radicle::node::address;
|
||||
use radicle::node::address::Store as _;
|
||||
use radicle::node::Handle as _;
|
||||
use radicle::node::{ADDRESS_DB_FILE, NODE_ANNOUNCEMENT_FILE, ROUTING_DB_FILE, TRACKING_DB_FILE};
|
||||
use radicle::profile::Home;
|
||||
use radicle::Storage;
|
||||
|
||||
@@ -42,15 +41,18 @@ pub enum Error {
|
||||
/// A routing database error.
|
||||
#[error("routing database error: {0}")]
|
||||
Routing(#[from] routing::Error),
|
||||
/// An address database error.
|
||||
#[error("address database error: {0}")]
|
||||
Addresses(#[from] address::Error),
|
||||
/// A node database error.
|
||||
#[error("node database error: {0}")]
|
||||
Database(#[from] node::db::Error),
|
||||
/// A tracking database error.
|
||||
#[error("tracking database error: {0}")]
|
||||
Tracking(#[from] tracking::Error),
|
||||
/// A gossip database error.
|
||||
#[error("gossip database error: {0}")]
|
||||
Gossip(#[from] gossip::Error),
|
||||
/// An address database error.
|
||||
#[error("address database error: {0}")]
|
||||
Address(#[from] address::Error),
|
||||
/// An I/O error.
|
||||
#[error("i/o error: {0}")]
|
||||
Io(#[from] io::Error),
|
||||
@@ -137,29 +139,20 @@ impl Runtime {
|
||||
let rng = fastrand::Rng::new();
|
||||
let clock = LocalTime::now();
|
||||
let storage = Storage::open(home.storage(), git::UserInfo { alias, key: id })?;
|
||||
let address_db = node_dir.join(ADDRESS_DB_FILE);
|
||||
let routing_db = node_dir.join(ROUTING_DB_FILE);
|
||||
let tracking_db = node_dir.join(TRACKING_DB_FILE);
|
||||
let scope = config.scope;
|
||||
let policy = config.policy;
|
||||
|
||||
log::info!(target: "node", "Opening address book {}..", address_db.display());
|
||||
let mut addresses = address::Book::open(address_db.clone())?;
|
||||
log::info!(target: "node", "Opening node database..");
|
||||
let mut db: service::Stores<_> = home.database_mut()?.into();
|
||||
|
||||
log::info!(target: "node", "Opening gossip store from {}..", address_db.display());
|
||||
let gossip = gossip::Store::open(address_db)?; // Nb. same database as address book.
|
||||
|
||||
log::info!(target: "node", "Opening routing table {}..", routing_db.display());
|
||||
let routing = routing::Table::open(routing_db)?;
|
||||
|
||||
log::info!(target: "node", "Opening tracking policy table {}..", tracking_db.display());
|
||||
let tracking = tracking::Store::open(tracking_db.clone())?;
|
||||
log::info!(target: "node", "Opening tracking policy configuration..");
|
||||
let tracking = home.tracking_mut()?;
|
||||
let tracking = tracking::Config::new(policy, scope, tracking);
|
||||
|
||||
log::info!(target: "node", "Default tracking policy set to '{}'", &policy);
|
||||
log::info!(target: "node", "Initializing service ({:?})..", network);
|
||||
|
||||
let announcement = if let Some(ann) = fs::read(node_dir.join(NODE_ANNOUNCEMENT_FILE))
|
||||
let announcement = if let Some(ann) = fs::read(node_dir.join(node::NODE_ANNOUNCEMENT_FILE))
|
||||
.ok()
|
||||
.and_then(|ann| NodeAnnouncement::decode(&mut ann.as_slice()).ok())
|
||||
.and_then(|ann| {
|
||||
@@ -185,13 +178,13 @@ impl Runtime {
|
||||
.expect("Runtime::init: unable to solve proof-of-work puzzle")
|
||||
};
|
||||
|
||||
if config.connect.is_empty() && addresses.is_empty()? {
|
||||
if config.connect.is_empty() && db.addresses().is_empty()? {
|
||||
log::info!(target: "node", "Address book is empty. Adding bootstrap nodes..");
|
||||
|
||||
for (alias, addr) in config.network.bootstrap() {
|
||||
let (id, addr) = addr.into();
|
||||
|
||||
addresses.insert(
|
||||
db.addresses_mut().insert(
|
||||
&id,
|
||||
radicle::node::Features::SEED,
|
||||
alias,
|
||||
@@ -200,17 +193,15 @@ impl Runtime {
|
||||
[node::KnownAddress::new(addr, address::Source::Bootstrap)],
|
||||
)?;
|
||||
}
|
||||
log::info!(target: "node", "{} nodes added to address book", addresses.len()?);
|
||||
log::info!(target: "node", "{} nodes added to address book", db.addresses().len()?);
|
||||
}
|
||||
|
||||
let emitter: Emitter<Event> = Default::default();
|
||||
let service = service::Service::new(
|
||||
config,
|
||||
clock,
|
||||
routing,
|
||||
db,
|
||||
storage.clone(),
|
||||
addresses,
|
||||
gossip,
|
||||
tracking,
|
||||
signer.clone(),
|
||||
rng,
|
||||
@@ -246,7 +237,7 @@ impl Runtime {
|
||||
let fetch = worker::FetchConfig {
|
||||
policy,
|
||||
scope,
|
||||
tracking_db,
|
||||
tracking_db: home.node().join(node::TRACKING_DB_FILE),
|
||||
limit: FetchLimit::default(),
|
||||
local: nid,
|
||||
expiry: worker::garbage::Expiry::default(),
|
||||
|
||||
+137
-68
@@ -21,9 +21,14 @@ use localtime::{LocalDuration, LocalTime};
|
||||
use log::*;
|
||||
use nonempty::NonEmpty;
|
||||
|
||||
use radicle::node;
|
||||
use radicle::node::address;
|
||||
use radicle::node::address::Store as _;
|
||||
use radicle::node::address::{AddressBook, KnownAddress};
|
||||
use radicle::node::config::PeerConfig;
|
||||
use radicle::node::routing::Store as _;
|
||||
use radicle::node::seed;
|
||||
use radicle::node::seed::Store as _;
|
||||
use radicle::node::ConnectOptions;
|
||||
use radicle::storage::RepositoryError;
|
||||
|
||||
@@ -37,6 +42,7 @@ use crate::node::{
|
||||
};
|
||||
use crate::prelude::*;
|
||||
use crate::runtime::Emitter;
|
||||
use crate::service::gossip::Store as _;
|
||||
use crate::service::message::{Announcement, AnnouncementMessage, Info, Ping};
|
||||
use crate::service::message::{NodeAnnouncement, RefsAnnouncement};
|
||||
use crate::service::tracking::{store::Write, Scope};
|
||||
@@ -128,7 +134,11 @@ pub enum Error {
|
||||
#[error(transparent)]
|
||||
Routing(#[from] routing::Error),
|
||||
#[error(transparent)]
|
||||
Addresses(#[from] address::Error),
|
||||
Address(#[from] address::Error),
|
||||
#[error(transparent)]
|
||||
Database(#[from] node::db::Error),
|
||||
#[error(transparent)]
|
||||
Seeds(#[from] seed::Error),
|
||||
#[error(transparent)]
|
||||
Tracking(#[from] tracking::Error),
|
||||
#[error(transparent)]
|
||||
@@ -137,6 +147,11 @@ pub enum Error {
|
||||
Namespaces(#[from] NamespacesError),
|
||||
}
|
||||
|
||||
/// A store for all node data.
|
||||
pub trait Store: address::Store + gossip::Store + routing::Store + seed::Store {}
|
||||
|
||||
impl Store for node::Database {}
|
||||
|
||||
/// Function used to query internal service state.
|
||||
pub type QueryState = dyn Fn(&dyn ServiceState) -> Result<(), CommandError> + Send + Sync;
|
||||
|
||||
@@ -223,23 +238,74 @@ struct FetchState {
|
||||
subscribers: Vec<chan::Sender<FetchResult>>,
|
||||
}
|
||||
|
||||
/// Holds all node stores.
|
||||
#[derive(Debug)]
|
||||
pub struct Stores<D>(D);
|
||||
|
||||
impl<D> Stores<D>
|
||||
where
|
||||
D: Store,
|
||||
{
|
||||
/// Get the database as a routing store.
|
||||
pub fn routing(&self) -> &impl routing::Store {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Get the database as a routing store, mutably.
|
||||
pub fn routing_mut(&mut self) -> &mut impl routing::Store {
|
||||
&mut self.0
|
||||
}
|
||||
|
||||
/// Get the database as an address store.
|
||||
pub fn addresses(&self) -> &impl address::Store {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Get the database as an address store, mutably.
|
||||
pub fn addresses_mut(&mut self) -> &mut impl address::Store {
|
||||
&mut self.0
|
||||
}
|
||||
|
||||
/// Get the database as a gossip store.
|
||||
pub fn gossip(&self) -> &impl gossip::Store {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Get the database as a gossip store, mutably.
|
||||
pub fn gossip_mut(&mut self) -> &mut impl gossip::Store {
|
||||
&mut self.0
|
||||
}
|
||||
|
||||
/// Get the database as a seed store.
|
||||
pub fn seeds(&self) -> &impl seed::Store {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Get the database as a seed store, mutably.
|
||||
pub fn seeds_mut(&mut self) -> &mut impl seed::Store {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> From<D> for Stores<D> {
|
||||
fn from(db: D) -> Self {
|
||||
Self(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// The node service.
|
||||
#[derive(Debug)]
|
||||
pub struct Service<R, A, S, G> {
|
||||
pub struct Service<D, S, G> {
|
||||
/// Service configuration.
|
||||
config: Config,
|
||||
/// Our cryptographic signer and key.
|
||||
signer: G,
|
||||
/// Project storage.
|
||||
storage: S,
|
||||
/// Network routing table. Keeps track of where projects are located.
|
||||
routing: R,
|
||||
/// Node address manager.
|
||||
addresses: A,
|
||||
/// Node database.
|
||||
db: Stores<D>,
|
||||
/// Tracking policy configuration.
|
||||
tracking: tracking::Config<Write>,
|
||||
/// State relating to gossip.
|
||||
gossip: gossip::Store,
|
||||
/// Peer sessions, currently or recently connected.
|
||||
sessions: Sessions,
|
||||
/// Clock. Tells the time.
|
||||
@@ -272,7 +338,7 @@ pub struct Service<R, A, S, G> {
|
||||
emitter: Emitter<Event>,
|
||||
}
|
||||
|
||||
impl<R, A, S, G> Service<R, A, S, G>
|
||||
impl<D, S, G> Service<D, S, G>
|
||||
where
|
||||
G: crypto::Signer,
|
||||
{
|
||||
@@ -287,20 +353,17 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, A, S, G> Service<R, A, S, G>
|
||||
impl<D, S, G> Service<D, S, G>
|
||||
where
|
||||
R: routing::Store,
|
||||
A: address::Store,
|
||||
D: Store,
|
||||
S: ReadStorage + 'static,
|
||||
G: Signer,
|
||||
{
|
||||
pub fn new(
|
||||
config: Config,
|
||||
clock: LocalTime,
|
||||
routing: R,
|
||||
db: Stores<D>,
|
||||
storage: S,
|
||||
addresses: A,
|
||||
gossip: gossip::Store,
|
||||
tracking: tracking::Config<Write>,
|
||||
signer: G,
|
||||
rng: Rng,
|
||||
@@ -312,14 +375,12 @@ where
|
||||
Self {
|
||||
config,
|
||||
storage,
|
||||
addresses,
|
||||
tracking,
|
||||
signer,
|
||||
rng,
|
||||
node,
|
||||
clock,
|
||||
routing,
|
||||
gossip,
|
||||
db,
|
||||
outbox: Outbox::default(),
|
||||
limiter: RateLimiter::default(),
|
||||
sessions,
|
||||
@@ -382,19 +443,14 @@ where
|
||||
todo!()
|
||||
}
|
||||
|
||||
/// Get the address book instance.
|
||||
pub fn addresses(&self) -> &A {
|
||||
&self.addresses
|
||||
/// Get the database.
|
||||
pub fn database(&self) -> &Stores<D> {
|
||||
&self.db
|
||||
}
|
||||
|
||||
/// Get the mutable address book instance.
|
||||
pub fn addresses_mut(&mut self) -> &mut A {
|
||||
&mut self.addresses
|
||||
}
|
||||
|
||||
/// Get the routing store.
|
||||
pub fn routing(&self) -> &R {
|
||||
&self.routing
|
||||
/// Get the mutable database.
|
||||
pub fn database_mut(&mut self) -> &mut Stores<D> {
|
||||
&mut self.db
|
||||
}
|
||||
|
||||
/// Get the storage instance.
|
||||
@@ -427,9 +483,9 @@ where
|
||||
&mut self.outbox
|
||||
}
|
||||
|
||||
/// Lookup a project, both locally and in the routing table.
|
||||
/// Lookup a repository, both locally and in the routing table.
|
||||
pub fn lookup(&self, rid: Id) -> Result<Lookup, LookupError> {
|
||||
let remote = self.routing.get(&rid)?.iter().cloned().collect();
|
||||
let remote = self.db.routing().get(&rid)?.iter().cloned().collect();
|
||||
|
||||
Ok(Lookup {
|
||||
local: self.storage.get(rid)?,
|
||||
@@ -440,12 +496,14 @@ where
|
||||
pub fn initialize(&mut self, time: LocalTime) -> Result<(), Error> {
|
||||
debug!(target: "service", "Init @{}", time.as_millis());
|
||||
|
||||
let nid = self.node_id();
|
||||
self.start_time = time;
|
||||
|
||||
// Ensure that our local node is in our address database.
|
||||
self.addresses
|
||||
self.db
|
||||
.addresses_mut()
|
||||
.insert(
|
||||
&self.node_id(),
|
||||
&nid,
|
||||
self.node.features,
|
||||
self.node.alias.clone(),
|
||||
self.node.work(),
|
||||
@@ -466,12 +524,11 @@ where
|
||||
// all of it. It can happen that inventory is not properly tracked if for eg. the
|
||||
// user creates a new repository while the node is stopped.
|
||||
let rids = self.storage.inventory()?;
|
||||
self.routing
|
||||
.insert(&rids, self.node_id(), time.as_millis())?;
|
||||
self.db.routing_mut().insert(&rids, nid, time.as_millis())?;
|
||||
|
||||
let nid = self.node_id();
|
||||
let announced = self
|
||||
.addresses
|
||||
.db
|
||||
.seeds()
|
||||
.seeded_by(&nid)?
|
||||
.collect::<Result<HashMap<_, _>, _>>()?;
|
||||
for rid in rids {
|
||||
@@ -493,15 +550,19 @@ where
|
||||
}
|
||||
// Make sure our local node's sync status is up to date with storage.
|
||||
debug!(target: "service", "Saving local sync status for {rid}..");
|
||||
self.addresses
|
||||
.synced(&rid, &nid, updated_at.oid, updated_at.timestamp.as_millis())?;
|
||||
self.db.seeds_mut().synced(
|
||||
&rid,
|
||||
&nid,
|
||||
updated_at.oid,
|
||||
updated_at.timestamp.as_millis(),
|
||||
)?;
|
||||
|
||||
// If we got here, it likely means a repo was updated while the node was stopped.
|
||||
// Therefore, we pre-load a refs announcement for this repo, so that it is included in
|
||||
// the historical gossip messages when a node connects and subscribes to this repo.
|
||||
if let Ok((ann, _)) = self.refs_announcement_for(rid, [nid]) {
|
||||
debug!(target: "service", "Adding refs announcement for {rid} to historical gossip messages..");
|
||||
self.gossip.announced(&nid, &ann)?;
|
||||
self.db.gossip_mut().announced(&nid, &ann)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -566,7 +627,8 @@ where
|
||||
error!(target: "service", "Error pruning routing entries: {err}");
|
||||
}
|
||||
if let Err(err) = self
|
||||
.gossip
|
||||
.db
|
||||
.gossip_mut()
|
||||
.prune((now - self.config.limits.gossip_max_age).as_millis())
|
||||
{
|
||||
error!(target: "service", "Error pruning gossip entries: {err}");
|
||||
@@ -925,7 +987,7 @@ where
|
||||
peer.to_connected(self.clock);
|
||||
self.outbox.write_all(peer, msgs);
|
||||
|
||||
if let Err(e) = self.addresses.connected(&remote, &peer.addr, now) {
|
||||
if let Err(e) = self.db.addresses_mut().connected(&remote, &peer.addr, now) {
|
||||
error!(target: "service", "Error updating address book with connection: {e}");
|
||||
}
|
||||
}
|
||||
@@ -1000,7 +1062,8 @@ where
|
||||
debug!(target: "service", "Dropping peer {remote}..");
|
||||
|
||||
if let Err(e) =
|
||||
self.addresses
|
||||
self.db
|
||||
.addresses_mut()
|
||||
.disconnected(&remote, &session.addr, reason.is_transient())
|
||||
{
|
||||
error!(target: "service", "Error updating address store: {e}");
|
||||
@@ -1068,7 +1131,7 @@ where
|
||||
// announcement timestamp, but before the other announcements. In that case, we simply
|
||||
// ignore all announcements of that node until we get a node announcement.
|
||||
if let AnnouncementMessage::Inventory(_) | AnnouncementMessage::Refs(_) = message {
|
||||
match self.addresses.get(announcer) {
|
||||
match self.db.addresses().get(announcer) {
|
||||
Ok(node) => {
|
||||
if node.is_none() {
|
||||
debug!(target: "service", "Ignoring announcement from unknown node {announcer}");
|
||||
@@ -1083,7 +1146,7 @@ where
|
||||
}
|
||||
|
||||
// Discard announcement messages we've already seen, otherwise update our last seen time.
|
||||
match self.gossip.announced(announcer, announcement) {
|
||||
match self.db.gossip_mut().announced(announcer, announcement) {
|
||||
Ok(fresh) => {
|
||||
if !fresh {
|
||||
trace!(target: "service", "Ignoring stale inventory announcement from {announcer} (t={})", self.time());
|
||||
@@ -1162,7 +1225,8 @@ where
|
||||
// We update inventories when receiving ref announcements, as these could come
|
||||
// from a new repository being initialized.
|
||||
if let Ok(result) =
|
||||
self.routing
|
||||
self.db
|
||||
.routing_mut()
|
||||
.insert([&message.rid], *announcer, message.timestamp)
|
||||
{
|
||||
if let &[(_, InsertResult::SeedAdded)] = result.as_slice() {
|
||||
@@ -1176,10 +1240,12 @@ where
|
||||
|
||||
// Update sync status for this repo.
|
||||
if let Some(refs) = message.refs.iter().find(|r| &r.remote == self.nid()) {
|
||||
match self
|
||||
.addresses
|
||||
.synced(&message.rid, announcer, refs.at, message.timestamp)
|
||||
{
|
||||
match self.db.seeds_mut().synced(
|
||||
&message.rid,
|
||||
announcer,
|
||||
refs.at,
|
||||
message.timestamp,
|
||||
) {
|
||||
Ok(updated) => {
|
||||
if updated {
|
||||
debug!(
|
||||
@@ -1295,7 +1361,7 @@ where
|
||||
return Ok(relay);
|
||||
}
|
||||
|
||||
match self.addresses.insert(
|
||||
match self.db.addresses_mut().insert(
|
||||
announcer,
|
||||
*features,
|
||||
ann.alias.clone(),
|
||||
@@ -1426,7 +1492,8 @@ where
|
||||
(session::State::Connected { .. }, Message::Subscribe(subscribe)) => {
|
||||
// Filter announcements by interest.
|
||||
match self
|
||||
.gossip
|
||||
.db
|
||||
.gossip()
|
||||
.filtered(&subscribe.filter, subscribe.since, subscribe.until)
|
||||
{
|
||||
Ok(anns) => {
|
||||
@@ -1507,7 +1574,7 @@ where
|
||||
//
|
||||
// If this is our first connection to the network, we just ask for a fixed backlog
|
||||
// of messages to get us started.
|
||||
let since = match self.gossip.last() {
|
||||
let since = match self.db.gossip().last() {
|
||||
Ok(Some(last)) => last - MAX_TIME_DELTA.as_millis() as Timestamp,
|
||||
Ok(None) => (*now - INITIAL_SUBSCRIBE_BACKLOG_DELTA).as_millis() as Timestamp,
|
||||
Err(e) => {
|
||||
@@ -1545,7 +1612,7 @@ where
|
||||
let mut synced = SyncedRouting::default();
|
||||
let included: HashSet<&Id> = HashSet::from_iter(inventory);
|
||||
|
||||
for (rid, result) in self.routing.insert(inventory, from, timestamp)? {
|
||||
for (rid, result) in self.db.routing_mut().insert(inventory, from, timestamp)? {
|
||||
match result {
|
||||
InsertResult::SeedAdded => {
|
||||
info!(target: "service", "Routing table updated for {rid} with seed {from}");
|
||||
@@ -1565,9 +1632,9 @@ where
|
||||
InsertResult::NotUpdated => {}
|
||||
}
|
||||
}
|
||||
for rid in self.routing.get_resources(&from)?.into_iter() {
|
||||
for rid in self.db.routing().get_resources(&from)?.into_iter() {
|
||||
if !included.contains(&rid) {
|
||||
if self.routing.remove(&rid, &from)? {
|
||||
if self.db.routing_mut().remove(&rid, &from)? {
|
||||
synced.removed.push(rid);
|
||||
self.emitter.emit(Event::SeedDropped { rid, nid: from });
|
||||
}
|
||||
@@ -1622,7 +1689,8 @@ where
|
||||
// the node was stopped.
|
||||
if let Some(refs) = refs.iter().find(|r| r.remote == ann.node) {
|
||||
if let Err(e) = self
|
||||
.addresses
|
||||
.db
|
||||
.seeds_mut()
|
||||
.synced(&rid, &ann.node, refs.at, ann.timestamp())
|
||||
{
|
||||
error!(target: "service", "Error updating sync status for local node: {e}");
|
||||
@@ -1634,7 +1702,7 @@ where
|
||||
// Only announce to peers who are allowed to view this repo.
|
||||
doc.is_visible_to(&p.id)
|
||||
}),
|
||||
&mut self.gossip,
|
||||
self.db.gossip_mut(),
|
||||
);
|
||||
|
||||
Ok(refs)
|
||||
@@ -1682,8 +1750,9 @@ where
|
||||
return false;
|
||||
}
|
||||
let persistent = self.config.is_persistent(&nid);
|
||||
let time = self.time();
|
||||
|
||||
if let Err(e) = self.addresses.attempted(&nid, &addr, self.time()) {
|
||||
if let Err(e) = self.db.addresses_mut().attempted(&nid, &addr, time) {
|
||||
error!(target: "service", "Error updating address book with connection attempt: {e}");
|
||||
}
|
||||
self.sessions.insert(
|
||||
@@ -1709,7 +1778,7 @@ where
|
||||
// our own refs.
|
||||
if let Ok(repo) = self.storage.repository(*rid) {
|
||||
if let Ok(local) = RefsAt::new(&repo, self.node_id()) {
|
||||
for seed in self.addresses.seeds(rid)? {
|
||||
for seed in self.db.seeds().seeds_for(rid)? {
|
||||
let seed = seed?;
|
||||
let state = self.sessions.get(&seed.nid).map(|s| s.state.clone());
|
||||
let synced = if local.at == seed.synced_at.oid {
|
||||
@@ -1730,7 +1799,7 @@ where
|
||||
// Then, add peers we know about but have no information about the sync status.
|
||||
// These peers have announced that they track the repository via an inventory
|
||||
// announcement, but we haven't received any ref announcements from them.
|
||||
for nid in self.routing.get(rid)? {
|
||||
for nid in self.db.routing().get(rid)? {
|
||||
if nid == self.node_id() {
|
||||
continue;
|
||||
}
|
||||
@@ -1738,7 +1807,7 @@ where
|
||||
// We already have a richer entry for this node.
|
||||
continue;
|
||||
}
|
||||
let addrs = self.addresses.addresses(&nid)?;
|
||||
let addrs = self.db.addresses().addresses_of(&nid)?;
|
||||
let state = self.sessions.get(&nid).map(|s| s.state.clone());
|
||||
|
||||
seeds.insert(Seed::new(nid, addrs, state, None));
|
||||
@@ -1773,19 +1842,19 @@ where
|
||||
self.outbox.announce(
|
||||
msg.signed(&self.signer),
|
||||
self.sessions.connected().map(|(_, p)| p),
|
||||
&mut self.gossip,
|
||||
self.db.gossip_mut(),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn prune_routing_entries(&mut self, now: &LocalTime) -> Result<(), routing::Error> {
|
||||
let count = self.routing.len()?;
|
||||
let count = self.db.routing().len()?;
|
||||
if count <= self.config.limits.routing_max_size {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let delta = count - self.config.limits.routing_max_size;
|
||||
self.routing.prune(
|
||||
self.db.routing_mut().prune(
|
||||
(*now - self.config.limits.routing_max_age).as_millis(),
|
||||
Some(delta),
|
||||
)?;
|
||||
@@ -1825,7 +1894,7 @@ where
|
||||
|
||||
/// Get a list of peers available to connect to.
|
||||
fn available_peers(&mut self) -> HashMap<NodeId, Vec<KnownAddress>> {
|
||||
match self.addresses.entries() {
|
||||
match self.db.addresses().entries() {
|
||||
Ok(entries) => {
|
||||
// Nb. we don't want to connect to any peers that already have a session with us,
|
||||
// even if it's in a disconnected state. Those sessions are re-attempted automatically.
|
||||
@@ -1969,9 +2038,9 @@ pub trait ServiceState {
|
||||
fn config(&self) -> &Config;
|
||||
}
|
||||
|
||||
impl<R, A, S, G> ServiceState for Service<R, A, S, G>
|
||||
impl<D, S, G> ServiceState for Service<D, S, G>
|
||||
where
|
||||
R: routing::Store,
|
||||
D: routing::Store,
|
||||
G: Signer,
|
||||
S: ReadStorage,
|
||||
{
|
||||
|
||||
@@ -3,7 +3,7 @@ pub mod store;
|
||||
use super::*;
|
||||
|
||||
pub use store::Error;
|
||||
pub use store::GossipStore as Store;
|
||||
pub use store::Store;
|
||||
|
||||
pub fn node(config: &Config, timestamp: Timestamp) -> NodeAnnouncement {
|
||||
let features = config.features();
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use std::{fmt, io, path::Path};
|
||||
use std::{fmt, io};
|
||||
|
||||
use radicle::crypto::Signature;
|
||||
use sqlite as sql;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::node::NodeId;
|
||||
use crate::node::{Database, NodeId};
|
||||
use crate::prelude::{Filter, Timestamp};
|
||||
use crate::service::message::{
|
||||
Announcement, AnnouncementMessage, InventoryAnnouncement, NodeAnnouncement, RefsAnnouncement,
|
||||
@@ -14,39 +14,42 @@ use crate::wire::Decode;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum Error {
|
||||
/// I/O error.
|
||||
#[error("i/o error: {0}")]
|
||||
Io(#[from] io::Error),
|
||||
/// An Internal error.
|
||||
#[error("internal error: {0}")]
|
||||
Internal(#[from] sql::Error),
|
||||
}
|
||||
|
||||
/// A database that has access to historical gossip messages.
|
||||
/// Keeps track of the latest received gossip messages for each node.
|
||||
/// Grows linearly with the number of nodes on the network.
|
||||
pub struct GossipStore {
|
||||
db: sql::Connection,
|
||||
}
|
||||
|
||||
impl fmt::Debug for GossipStore {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("GossipStore").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl GossipStore {
|
||||
/// Open a gossip store at the given path. Creates a new store if it doesn't exist.
|
||||
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
|
||||
let db = sql::Connection::open_with_flags(
|
||||
path,
|
||||
sqlite::OpenFlags::new().with_read_write().with_full_mutex(),
|
||||
)?;
|
||||
|
||||
Ok(Self { db })
|
||||
}
|
||||
|
||||
pub trait Store {
|
||||
/// Prune announcements older than the cutoff time.
|
||||
pub fn prune(&mut self, cutoff: Timestamp) -> Result<usize, Error> {
|
||||
fn prune(&mut self, cutoff: Timestamp) -> Result<usize, Error>;
|
||||
|
||||
/// Get the timestamp of the last announcement in the store.
|
||||
fn last(&self) -> Result<Option<Timestamp>, Error>;
|
||||
|
||||
/// Process an announcement for the given node.
|
||||
/// Returns `true` if the timestamp was updated or the announcement wasn't there before.
|
||||
fn announced(&mut self, nid: &NodeId, ann: &Announcement) -> Result<bool, Error>;
|
||||
|
||||
/// Get all the latest gossip messages of all nodes, filtered by inventory filter and
|
||||
/// announcement timestamps.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `from` > `to`.
|
||||
///
|
||||
fn filtered<'a>(
|
||||
&'a self,
|
||||
filter: &'a Filter,
|
||||
from: Timestamp,
|
||||
to: Timestamp,
|
||||
) -> Result<Box<dyn Iterator<Item = Result<Announcement, Error>> + 'a>, Error>;
|
||||
}
|
||||
|
||||
impl Store for Database {
|
||||
fn prune(&mut self, cutoff: Timestamp) -> Result<usize, Error> {
|
||||
let mut stmt = self
|
||||
.db
|
||||
.prepare("DELETE FROM `announcements` WHERE timestamp < ?1")?;
|
||||
@@ -57,8 +60,7 @@ impl GossipStore {
|
||||
Ok(self.db.change_count())
|
||||
}
|
||||
|
||||
/// Get the timestamp of the last announcement in the store.
|
||||
pub fn last(&self) -> Result<Option<Timestamp>, Error> {
|
||||
fn last(&self) -> Result<Option<Timestamp>, Error> {
|
||||
let stmt = self
|
||||
.db
|
||||
.prepare("SELECT MAX(timestamp) AS latest FROM `announcements`")?;
|
||||
@@ -71,9 +73,7 @@ impl GossipStore {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Process an announcement for the given node.
|
||||
/// Returns `true` if the timestamp was updated or the announcement wasn't there before.
|
||||
pub fn announced(&mut self, nid: &NodeId, ann: &Announcement) -> Result<bool, Error> {
|
||||
fn announced(&mut self, nid: &NodeId, ann: &Announcement) -> Result<bool, Error> {
|
||||
let mut stmt = self.db.prepare(
|
||||
"INSERT INTO `announcements` (node, repo, type, message, signature, timestamp)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
|
||||
@@ -107,19 +107,12 @@ impl GossipStore {
|
||||
Ok(self.db.change_count() > 0)
|
||||
}
|
||||
|
||||
/// Get all the latest gossip messages of all nodes, filtered by inventory filter and
|
||||
/// announcement timestamps.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `from` > `to`.
|
||||
///
|
||||
pub fn filtered<'a>(
|
||||
fn filtered<'a>(
|
||||
&'a self,
|
||||
filter: &'a Filter,
|
||||
from: Timestamp,
|
||||
to: Timestamp,
|
||||
) -> Result<impl Iterator<Item = Result<Announcement, Error>> + 'a, Error> {
|
||||
) -> Result<Box<dyn Iterator<Item = Result<Announcement, Error>> + 'a>, Error> {
|
||||
let mut stmt = self.db.prepare(
|
||||
"SELECT node, type, message, signature, timestamp
|
||||
FROM announcements
|
||||
@@ -131,41 +124,42 @@ impl GossipStore {
|
||||
stmt.bind((1, i64::try_from(from).unwrap_or(i64::MAX)))?;
|
||||
stmt.bind((2, i64::try_from(to).unwrap_or(i64::MAX)))?;
|
||||
|
||||
Ok(stmt
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let row = row?;
|
||||
let node = row.read::<NodeId, _>("node");
|
||||
let gt = row.read::<GossipType, _>("type");
|
||||
let message = match gt {
|
||||
GossipType::Refs => {
|
||||
let ann = row.read::<RefsAnnouncement, _>("message");
|
||||
AnnouncementMessage::Refs(ann)
|
||||
}
|
||||
GossipType::Inventory => {
|
||||
let ann = row.read::<InventoryAnnouncement, _>("message");
|
||||
AnnouncementMessage::Inventory(ann)
|
||||
}
|
||||
GossipType::Node => {
|
||||
let ann = row.read::<NodeAnnouncement, _>("message");
|
||||
AnnouncementMessage::Node(ann)
|
||||
}
|
||||
};
|
||||
let signature = row.read::<Signature, _>("signature");
|
||||
let timestamp = row.read::<i64, _>("timestamp");
|
||||
Ok(Box::new(
|
||||
stmt.into_iter()
|
||||
.map(|row| {
|
||||
let row = row?;
|
||||
let node = row.read::<NodeId, _>("node");
|
||||
let gt = row.read::<GossipType, _>("type");
|
||||
let message = match gt {
|
||||
GossipType::Refs => {
|
||||
let ann = row.read::<RefsAnnouncement, _>("message");
|
||||
AnnouncementMessage::Refs(ann)
|
||||
}
|
||||
GossipType::Inventory => {
|
||||
let ann = row.read::<InventoryAnnouncement, _>("message");
|
||||
AnnouncementMessage::Inventory(ann)
|
||||
}
|
||||
GossipType::Node => {
|
||||
let ann = row.read::<NodeAnnouncement, _>("message");
|
||||
AnnouncementMessage::Node(ann)
|
||||
}
|
||||
};
|
||||
let signature = row.read::<Signature, _>("signature");
|
||||
let timestamp = row.read::<i64, _>("timestamp");
|
||||
|
||||
debug_assert_eq!(timestamp, message.timestamp() as i64);
|
||||
debug_assert_eq!(timestamp, message.timestamp() as i64);
|
||||
|
||||
Ok(Announcement {
|
||||
node,
|
||||
message,
|
||||
signature,
|
||||
Ok(Announcement {
|
||||
node,
|
||||
message,
|
||||
signature,
|
||||
})
|
||||
})
|
||||
})
|
||||
.filter(|ann| match ann {
|
||||
Ok(a) => a.matches(filter),
|
||||
Err(_) => true,
|
||||
}))
|
||||
.filter(|ann| match ann {
|
||||
Ok(a) => a.matches(filter),
|
||||
Err(_) => true,
|
||||
}),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ impl Outbox {
|
||||
&mut self,
|
||||
ann: Announcement,
|
||||
peers: impl Iterator<Item = &'a Session>,
|
||||
gossip: &mut gossip::Store,
|
||||
gossip: &mut impl gossip::Store,
|
||||
) {
|
||||
// Store our announcement so that it can be retrieved from us later, just like
|
||||
// announcements we receive from peers.
|
||||
|
||||
@@ -18,11 +18,10 @@ use radicle::crypto::{KeyPair, Seed, Signer};
|
||||
use radicle::git;
|
||||
use radicle::git::refname;
|
||||
use radicle::identity::{Id, Visibility};
|
||||
use radicle::node::address::Book;
|
||||
use radicle::node::routing;
|
||||
use radicle::node::routing::Store;
|
||||
use radicle::node::tracking::store as tracking;
|
||||
use radicle::node::{Alias, ADDRESS_DB_FILE, ROUTING_DB_FILE, TRACKING_DB_FILE};
|
||||
use radicle::node::Database;
|
||||
use radicle::node::{Alias, TRACKING_DB_FILE};
|
||||
use radicle::node::{ConnectOptions, Handle as _};
|
||||
use radicle::profile;
|
||||
use radicle::profile::Home;
|
||||
@@ -84,20 +83,15 @@ impl Environment {
|
||||
|
||||
let tracking_db = profile.home.node().join(TRACKING_DB_FILE);
|
||||
let tracking = tracking::Config::open(tracking_db).unwrap();
|
||||
|
||||
let routing_db = profile.home.node().join(ROUTING_DB_FILE);
|
||||
let routing = routing::Table::open(routing_db).unwrap();
|
||||
|
||||
let addresses_db = profile.home.node().join(ADDRESS_DB_FILE);
|
||||
let addresses = Book::open(addresses_db).unwrap();
|
||||
let db = profile.database_mut().unwrap();
|
||||
let db = service::Stores::from(db);
|
||||
|
||||
Node {
|
||||
id: *profile.id(),
|
||||
home: profile.home,
|
||||
config,
|
||||
signer,
|
||||
addresses,
|
||||
routing,
|
||||
db,
|
||||
tracking,
|
||||
storage: profile.storage,
|
||||
}
|
||||
@@ -129,8 +123,7 @@ impl Environment {
|
||||
.unwrap();
|
||||
|
||||
tracking::Config::open(tracking_db).unwrap();
|
||||
let addresses_db = home.node().join(ADDRESS_DB_FILE);
|
||||
Book::open(addresses_db).unwrap();
|
||||
home.database_mut().unwrap(); // Just create the database.
|
||||
|
||||
transport::local::register(storage.clone());
|
||||
keystore.store(keypair.clone(), "radicle", None).unwrap();
|
||||
@@ -155,8 +148,7 @@ pub struct Node<G> {
|
||||
pub signer: G,
|
||||
pub storage: Storage,
|
||||
pub config: Config,
|
||||
pub addresses: Book,
|
||||
pub routing: routing::Table,
|
||||
pub db: service::Stores<Database>,
|
||||
pub tracking: tracking::Config<tracking::Write>,
|
||||
}
|
||||
|
||||
@@ -217,7 +209,7 @@ impl<G: Signer + cyphernet::Ecdh> NodeHandle<G> {
|
||||
|
||||
/// Get routing table entries.
|
||||
pub fn routing(&self) -> impl Iterator<Item = (Id, NodeId)> {
|
||||
radicle::node::routing::Table::reader(self.home.node().join(radicle::node::ROUTING_DB_FILE))
|
||||
Database::reader(self.home.node().join(node::NODE_DB_FILE))
|
||||
.unwrap()
|
||||
.entries()
|
||||
.unwrap()
|
||||
@@ -356,9 +348,9 @@ impl Node<MockSigner> {
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let addresses = home.addresses_mut().unwrap();
|
||||
let tracking = home.tracking_mut().unwrap();
|
||||
let routing = home.routing_mut().unwrap();
|
||||
let db = home.database_mut().unwrap();
|
||||
let db = service::Stores::from(db);
|
||||
|
||||
log::debug!(target: "test", "Node::init {}: {}", config.alias, signer.public_key());
|
||||
Self {
|
||||
@@ -367,9 +359,8 @@ impl Node<MockSigner> {
|
||||
signer,
|
||||
storage,
|
||||
config,
|
||||
addresses,
|
||||
db,
|
||||
tracking,
|
||||
routing,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,8 @@ use std::str::FromStr;
|
||||
use log::*;
|
||||
|
||||
use radicle::identity::Visibility;
|
||||
use radicle::node::address::Store;
|
||||
use radicle::node::address::Store as _;
|
||||
use radicle::node::Database;
|
||||
use radicle::node::{address, Alias, ConnectOptions};
|
||||
use radicle::rad;
|
||||
use radicle::storage::refs::RefsAt;
|
||||
@@ -18,7 +19,6 @@ use crate::crypto::test::signer::MockSigner;
|
||||
use crate::crypto::Signer;
|
||||
use crate::identity::Id;
|
||||
use crate::node;
|
||||
use crate::node::routing;
|
||||
use crate::prelude::*;
|
||||
use crate::runtime::Emitter;
|
||||
use crate::service;
|
||||
@@ -36,7 +36,7 @@ use crate::Link;
|
||||
use crate::{LocalDuration, LocalTime};
|
||||
|
||||
/// Service instantiation used for testing.
|
||||
pub type Service<S, G> = service::Service<routing::Table, address::Book, S, G>;
|
||||
pub type Service<S, G> = service::Service<Database, S, G>;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Peer<S, G> {
|
||||
@@ -100,8 +100,7 @@ where
|
||||
|
||||
pub struct Config<G: Signer + 'static> {
|
||||
pub config: service::Config,
|
||||
pub addrs: address::Book,
|
||||
pub gossip: gossip::Store,
|
||||
pub db: Stores<node::Database>,
|
||||
pub local_time: LocalTime,
|
||||
pub policy: Policy,
|
||||
pub scope: Scope,
|
||||
@@ -115,13 +114,13 @@ impl Default for Config<MockSigner> {
|
||||
let mut rng = fastrand::Rng::new();
|
||||
let signer = MockSigner::new(&mut rng);
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let addrs = address::Book::open(tmp.path().join("addresses.db")).unwrap();
|
||||
let gossip = gossip::Store::open(tmp.path().join("addresses.db")).unwrap();
|
||||
let db = Database::open(tmp.path().join(node::NODE_DB_FILE))
|
||||
.unwrap()
|
||||
.into();
|
||||
|
||||
Config {
|
||||
config: service::Config::test(Alias::from_str("mocky").unwrap()),
|
||||
addrs,
|
||||
gossip,
|
||||
db,
|
||||
local_time: LocalTime::now(),
|
||||
policy: Policy::default(),
|
||||
scope: Scope::default(),
|
||||
@@ -163,7 +162,6 @@ where
|
||||
storage: S,
|
||||
mut config: Config<G>,
|
||||
) -> Self {
|
||||
let routing = routing::Table::memory().unwrap();
|
||||
let tracking = tracking::Store::<tracking::store::Write>::memory().unwrap();
|
||||
let mut tracking = tracking::Config::new(config.policy, config.scope, tracking);
|
||||
let id = *config.signer.public_key();
|
||||
@@ -181,10 +179,8 @@ where
|
||||
let service = Service::new(
|
||||
config.config,
|
||||
config.local_time,
|
||||
routing,
|
||||
config.db,
|
||||
storage,
|
||||
config.addrs,
|
||||
config.gossip,
|
||||
tracking,
|
||||
config.signer,
|
||||
config.rng.clone(),
|
||||
@@ -236,8 +232,9 @@ where
|
||||
pub fn import_addresses<'a>(&mut self, peers: impl IntoIterator<Item = &'a Self>) {
|
||||
let timestamp = self.timestamp();
|
||||
for peer in peers.into_iter() {
|
||||
let known_address = address::KnownAddress::new(peer.address(), address::Source::Peer);
|
||||
let known_address = node::KnownAddress::new(peer.address(), address::Source::Peer);
|
||||
self.service
|
||||
.database_mut()
|
||||
.addresses_mut()
|
||||
.insert(
|
||||
&peer.node_id(),
|
||||
|
||||
@@ -273,7 +273,7 @@ fn test_inventory_sync() {
|
||||
);
|
||||
|
||||
for proj in &projs {
|
||||
let seeds = alice.routing().get(proj).unwrap();
|
||||
let seeds = alice.database().routing().get(proj).unwrap();
|
||||
assert!(seeds.contains(&bob.node_id()));
|
||||
}
|
||||
}
|
||||
@@ -382,7 +382,7 @@ fn test_inventory_pruning() {
|
||||
|
||||
assert_eq!(
|
||||
test.expected_routing_table_size,
|
||||
alice.routing().len().unwrap()
|
||||
alice.database().routing().len().unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ use netservices::{NetConnection, NetProtocol, NetReader, NetWriter};
|
||||
use reactor::Timestamp;
|
||||
|
||||
use radicle::collections::RandomMap;
|
||||
use radicle::node::{address, routing, NodeId};
|
||||
use radicle::node::NodeId;
|
||||
use radicle::storage::WriteStorage;
|
||||
|
||||
use crate::crypto::Signer;
|
||||
@@ -316,9 +316,9 @@ impl Peers {
|
||||
}
|
||||
|
||||
/// Wire protocol implementation for a set of peers.
|
||||
pub struct Wire<R, S, W, G: Signer + Ecdh> {
|
||||
pub struct Wire<D, S, G: Signer + Ecdh> {
|
||||
/// Backing service instance.
|
||||
service: Service<R, S, W, G>,
|
||||
service: Service<D, S, G>,
|
||||
/// Worker pool interface.
|
||||
worker: chan::Sender<Task>,
|
||||
/// Used for authentication.
|
||||
@@ -331,15 +331,14 @@ pub struct Wire<R, S, W, G: Signer + Ecdh> {
|
||||
proxy: net::SocketAddr,
|
||||
}
|
||||
|
||||
impl<R, S, W, G> Wire<R, S, W, G>
|
||||
impl<D, S, G> Wire<D, S, G>
|
||||
where
|
||||
R: routing::Store,
|
||||
S: address::Store,
|
||||
W: WriteStorage + 'static,
|
||||
D: service::Store,
|
||||
S: WriteStorage + 'static,
|
||||
G: Signer + Ecdh<Pk = NodeId>,
|
||||
{
|
||||
pub fn new(
|
||||
mut service: Service<R, S, W, G>,
|
||||
mut service: Service<D, S, G>,
|
||||
worker: chan::Sender<Task>,
|
||||
signer: G,
|
||||
proxy: net::SocketAddr,
|
||||
@@ -450,11 +449,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, S, W, G> reactor::Handler for Wire<R, S, W, G>
|
||||
impl<D, S, G> reactor::Handler for Wire<D, S, G>
|
||||
where
|
||||
R: routing::Store + Send,
|
||||
S: address::Store + Send,
|
||||
W: WriteStorage + Send + 'static,
|
||||
D: service::Store + Send,
|
||||
S: WriteStorage + Send + 'static,
|
||||
G: Signer + Ecdh<Pk = NodeId> + Clone + Send,
|
||||
{
|
||||
type Listener = NetAccept<WireSession<G>>;
|
||||
@@ -742,11 +740,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, S, W, G> Iterator for Wire<R, S, W, G>
|
||||
impl<D, S, G> Iterator for Wire<D, S, G>
|
||||
where
|
||||
R: routing::Store,
|
||||
S: address::Store,
|
||||
W: WriteStorage + 'static,
|
||||
D: service::Store,
|
||||
S: WriteStorage + 'static,
|
||||
G: Signer + Ecdh<Pk = NodeId>,
|
||||
{
|
||||
type Item = Action<G>;
|
||||
|
||||
Reference in New Issue
Block a user