rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5 heartwood99c847adec17499e6d949302fba350ad6cb1d154
{
"request": "trigger",
"version": 1,
"event_type": "patch",
"repository": {
"id": "rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5",
"name": "heartwood",
"description": "Radicle Heartwood Protocol & Stack",
"private": false,
"default_branch": "master",
"delegates": [
"did:key:z6MksFqXN3Yhqk8pTJdUGLwATkRfQvwZXPqR2qMEhbS9wzpT",
"did:key:z6MkireRatUThvd3qzfKht1S44wpm4FEWSSa4PRMTSQZ3voM",
"did:key:z6MkkPvBfjP4bQmco5Dm7UGsX2ruDBieEHi8n9DVJWX5sTEz"
]
},
"action": "Created",
"patch": {
"id": "511ad5ad569fea9124a9ad4738431e42b5075675",
"author": {
"id": "did:key:z6MkireRatUThvd3qzfKht1S44wpm4FEWSSa4PRMTSQZ3voM",
"alias": null
},
"title": "`radicle-protocol`: Sans-IO-ification",
"state": {
"status": "draft",
"conflicts": []
},
"before": "1cd3ad078453b316dc7f1d4aeb637fc2f6af35e0",
"after": "99c847adec17499e6d949302fba350ad6cb1d154",
"commits": [
"99c847adec17499e6d949302fba350ad6cb1d154",
"8eaaae769407c100476a8d01310b028bcd2be373",
"db6337e73043b1ef35e28548ee556d566cf5fda0",
"1fde061794ea4dddb8beb8a3949c19bfcd3ab8c5",
"990c52accf82f248dfa5c59724bc4208358431bb",
"a2c0d12fa32b1e3eda9f8078b84e979953b10226",
"1a43ebeff41cea3750472e69bc953b27c257c408"
],
"target": "3fc92f83fe089263c470b328414d923227cf0e4a",
"labels": [],
"assignees": [],
"revisions": [
{
"id": "511ad5ad569fea9124a9ad4738431e42b5075675",
"author": {
"id": "did:key:z6MkireRatUThvd3qzfKht1S44wpm4FEWSSa4PRMTSQZ3voM",
"alias": null
},
"description": "Exploring the conversion of `radicle-protocol` into a true sans-IO approach.",
"base": "efeefd0daa35682a3ff07bd6c24d73248252149f",
"oid": "7698f637656e8a225e04018a316294d3b731754e",
"timestamp": 1753429876
},
{
"id": "da4871b6df673e412bff3e7f731f2009781f3ccf",
"author": {
"id": "did:key:z6MkireRatUThvd3qzfKht1S44wpm4FEWSSa4PRMTSQZ3voM",
"alias": null
},
"description": "Changes:\n- Rebased\n- First sketch of a `Connections` state machine",
"base": "a8dac56ca645fdd98955766f07abe7cdd8980e56",
"oid": "ba174752c6a62186f0e79e8759d65ac9edc166e5",
"timestamp": 1754575831
},
{
"id": "418864d9ea7d9ff97cda5c76af0dcf348845cc52",
"author": {
"id": "did:key:z6MkireRatUThvd3qzfKht1S44wpm4FEWSSa4PRMTSQZ3voM",
"alias": null
},
"description": "Adding a fetch state machine",
"base": "a8dac56ca645fdd98955766f07abe7cdd8980e56",
"oid": "69fe26ceccf605df3063be6c75a69c89ed23de06",
"timestamp": 1754655542
},
{
"id": "8fc57dbb32c0cd5f1d25a924b3e4f82030892d74",
"author": {
"id": "did:key:z6MkireRatUThvd3qzfKht1S44wpm4FEWSSa4PRMTSQZ3voM",
"alias": null
},
"description": "Adding more slices of Service and extending existing components",
"base": "1cd3ad078453b316dc7f1d4aeb637fc2f6af35e0",
"oid": "99c847adec17499e6d949302fba350ad6cb1d154",
"timestamp": 1755103797
}
]
}
}
{
"response": "triggered",
"run_id": {
"id": "5b3bf9c2-4f70-48d0-baf7-457d05f42d3d"
},
"info_url": "https://cci.rad.levitte.org//5b3bf9c2-4f70-48d0-baf7-457d05f42d3d.html"
}
Started at: 2026-09-07 21:34:33.971560+02:00
Commands:
$ rad clone rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5 .
✓ Creating checkout in ./...
✓ Remote cloudhead@z6MksFqXN3Yhqk8pTJdUGLwATkRfQvwZXPqR2qMEhbS9wzpT added
✓ Remote-tracking branch cloudhead@z6MksFqXN3Yhqk8pTJdUGLwATkRfQvwZXPqR2qMEhbS9wzpT/master created for z6MksFqXN3Yhqk8pTJdUGLwATkRfQvwZXPqR2qMEhbS9wzpT
✓ Remote fintohaps@z6MkireRatUThvd3qzfKht1S44wpm4FEWSSa4PRMTSQZ3voM added
✓ Remote-tracking branch fintohaps@z6MkireRatUThvd3qzfKht1S44wpm4FEWSSa4PRMTSQZ3voM/master created for z6MkireRatUThvd3qzfKht1S44wpm4FEWSSa4PRMTSQZ3voM
✓ Remote lorenz@z6MkkPvBfjP4bQmco5Dm7UGsX2ruDBieEHi8n9DVJWX5sTEz added
✓ Remote-tracking branch lorenz@z6MkkPvBfjP4bQmco5Dm7UGsX2ruDBieEHi8n9DVJWX5sTEz/master created for z6MkkPvBfjP4bQmco5Dm7UGsX2ruDBieEHi8n9DVJWX5sTEz
✓ Repository successfully cloned under /opt/radcis/ci.rad.levitte.org/cci/state/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/
╭────────────────────────────────────╮
│ heartwood │
│ Radicle Heartwood Protocol & Stack │
│ 189 issues · 38 patches │
╰────────────────────────────────────╯
Run `cd ./.` to go to the repository directory.
Exit code: 0
$ rad patch checkout 511ad5ad569fea9124a9ad4738431e42b5075675
✓ Switched to branch patch/511ad5a at revision 8fc57db
✓ Branch patch/511ad5a setup to track rad/patches/511ad5ad569fea9124a9ad4738431e42b5075675
Exit code: 0
$ git config advice.detachedHead false
Exit code: 0
$ git checkout 99c847adec17499e6d949302fba350ad6cb1d154
HEAD is now at 99c847ad protocol: routing handler
Exit code: 0
$ rad patch show 511ad5ad569fea9124a9ad4738431e42b5075675 -p
╭───────────────────────────────────────────────────────────────────────────────╮
│ Title `radicle-protocol`: Sans-IO-ification │
│ Patch 511ad5ad569fea9124a9ad4738431e42b5075675 │
│ Author fintohaps z6Mkire…SQZ3voM │
│ Head 99c847adec17499e6d949302fba350ad6cb1d154 │
│ Base 1cd3ad078453b316dc7f1d4aeb637fc2f6af35e0 │
│ Target master │
│ Branches patch/511ad5a │
│ Commits ahead 7, behind 923 │
│ Status draft │
│ │
│ Exploring the conversion of `radicle-protocol` into a true sans-IO approach. │
├───────────────────────────────────────────────────────────────────────────────┤
│ 99c847a protocol: routing handler │
│ 8eaaae7 protocol(connections): pong command │
│ db6337e protocol: connections subscribe commands │
│ 1fde061 protocol: node events │
│ 990c52a protocol: fetch state │
│ a2c0d12 protocol: peer connections │
│ 1a43ebe protocol: port Service::wake to sans-IO │
├───────────────────────────────────────────────────────────────────────────────┤
│ ● Revision 511ad5a @ efeefd0..7698f63 by fintohaps z6Mkire…SQZ3voM 1 year ago │
│ ↑ Revision da4871b @ a8dac56..ba17475 by fintohaps z6Mkire…SQZ3voM 1 year ago │
│ ↑ Revision 418864d @ a8dac56..69fe26c by fintohaps z6Mkire…SQZ3voM 1 year ago │
│ ↑ Revision 8fc57db @ 1cd3ad0..99c847a by fintohaps z6Mkire…SQZ3voM 1 year ago │
╰───────────────────────────────────────────────────────────────────────────────╯
commit 99c847adec17499e6d949302fba350ad6cb1d154
Author: Fintan Halpenny <fintan.halpenny@gmail.com>
Date: Wed Aug 13 16:29:00 2025 +0100
protocol: routing handler
The method `Service::sync_routing` handles setting an announced
inventory from a node and keeps track of whether the RIDs are added,
updated, or removed. It does this by interacting with the routing
table.
To translate this into a sans I/O approach, the inventory is tracked
as a BTreeSet, that can then be compared against using
`BTreeSet::difference` calculations.
The effects of setting the inventory in the routing table is then
captured by a trait.
diff --git a/crates/radicle-protocol/src/lib.rs b/crates/radicle-protocol/src/lib.rs
index 37cdbc486..226cdc4fc 100644
--- a/crates/radicle-protocol/src/lib.rs
+++ b/crates/radicle-protocol/src/lib.rs
@@ -7,6 +7,7 @@ pub mod worker;
pub mod connections;
pub mod fetcher;
pub mod node;
+pub mod routing;
pub mod tasks;
/// Peer-to-peer protocol version.
diff --git a/crates/radicle-protocol/src/routing.rs b/crates/radicle-protocol/src/routing.rs
new file mode 100644
index 000000000..56307cc60
--- /dev/null
+++ b/crates/radicle-protocol/src/routing.rs
@@ -0,0 +1,115 @@
+pub mod effects;
+
+use std::collections::BTreeSet;
+
+use radicle::{
+ node::{NodeId, Timestamp},
+ prelude::RepoId,
+};
+
+/// Evaluate a node's inventory when a new inventory is announced.
+pub struct Routing {
+ node: NodeId,
+ inventory: BTreeSet<RepoId>,
+}
+
+impl Routing {
+ /// Construct the node's existing inventory.
+ pub fn new(node: NodeId, inventory: BTreeSet<RepoId>) -> Self {
+ Self { node, inventory }
+ }
+
+ /// When a new inventory has been found, evaluate it against the existing
+ /// inventory to see which repositories were added or removed.
+ pub fn found_inventory(&self, inventory: BTreeSet<RepoId>) -> RoutingResult {
+ let mut result = RoutingResult::default();
+ let existing = &self.inventory;
+ let removed = existing
+ .difference(&inventory)
+ .copied()
+ .collect::<BTreeSet<RepoId>>();
+ let added = inventory
+ .difference(existing)
+ .copied()
+ .collect::<BTreeSet<RepoId>>();
+
+ result.update(inventory);
+ result.added(self.node, added);
+ result.removed(self.node, removed);
+ result
+ }
+
+ /// Finalize the node's inventory and get the [`SetInventory`] for setting
+ /// the inventory in the [`RoutingTable`].
+ ///
+ /// [`SetInventory`]: effects::SetInventory
+ /// [`RoutingTable`]: effects::RoutingTable
+ pub fn set_inventory(self, now: Timestamp) -> effects::SetInventory {
+ effects::SetInventory {
+ node: self.node,
+ inventory: self.inventory,
+ now,
+ }
+ }
+}
+
+impl Routing {
+ /// Process a [`Command`] for the routing computation to update the state of
+ /// the node's inventory.
+ pub fn handle_command(&mut self, command: Command) {
+ match command {
+ Command::Update { inventory } => {
+ self.inventory = inventory;
+ }
+ }
+ }
+}
+
+/// Commands for advancing the [`Routing`] state.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Command {
+ /// Update the [`Routing`] state with the new inventory.
+ Update { inventory: BTreeSet<RepoId> },
+}
+
+/// Events that are emitted when evaluating the [`Routing`] state against new
+/// input.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Event {
+ /// The set of repositories were added for the node's routing table.
+ Added {
+ node: NodeId,
+ repos: BTreeSet<RepoId>,
+ },
+ /// The set of repositories were removed from the node's routing table.
+ Removed {
+ node: NodeId,
+ repos: BTreeSet<RepoId>,
+ },
+}
+
+/// The result of [`Routing::found_inventory`].
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct RoutingResult {
+ /// See [`Command`].
+ pub commands: Vec<Command>,
+ /// See [`Event`].
+ pub events: Vec<Event>,
+}
+
+impl RoutingResult {
+ fn update(&mut self, inventory: BTreeSet<RepoId>) {
+ self.commands.push(Command::Update { inventory });
+ }
+
+ fn added(&mut self, node: NodeId, added: BTreeSet<RepoId>) {
+ self.events.push(Event::Added { node, repos: added });
+ }
+
+ fn removed(&mut self, node: NodeId, removed: BTreeSet<RepoId>) {
+ self.events.push(Event::Removed {
+ node,
+ repos: removed,
+ });
+ }
+}
diff --git a/crates/radicle-protocol/src/routing/effects.rs b/crates/radicle-protocol/src/routing/effects.rs
new file mode 100644
index 000000000..e9abd411e
--- /dev/null
+++ b/crates/radicle-protocol/src/routing/effects.rs
@@ -0,0 +1,31 @@
+use std::collections::BTreeSet;
+
+use radicle::{
+ node::{NodeId, Timestamp},
+ prelude::RepoId,
+};
+
+pub struct SetInventory {
+ /// The node we are setting the inventory for.
+ pub node: NodeId,
+ /// The inventory of the node.
+ pub inventory: BTreeSet<RepoId>,
+ /// When the inventory update was found.
+ pub now: Timestamp,
+}
+
+/// An error occurred when setting the inventory for a node in the routing
+/// table.
+///
+/// Note that there are no domain errors for setting the inventory, since we
+/// expect it to always set the inventory.
+pub enum SetInventoryError {
+ /// An error occurred due to the underlying storage mechanism.
+ Other(Box<dyn std::error::Error + Send + Sync + 'static>),
+}
+
+pub trait RoutingTable {
+ /// Set the inventory for a node. The inventory is essentially the set of
+ /// RIDs that the node is seeding and replicating.
+ fn set_inventory(set: SetInventory) -> Result<(), SetInventoryError>;
+}
commit 8eaaae769407c100476a8d01310b028bcd2be373
Author: Fintan Halpenny <fintan.halpenny@gmail.com>
Date: Wed Aug 13 16:24:39 2025 +0100
protocol(connections): pong command
Introduce `Pong` command intended for when a node responds to a ping
message with a pong message, which gets recorded in the session for
the node.
diff --git a/crates/radicle-protocol/src/connections.rs b/crates/radicle-protocol/src/connections.rs
index dce945c4d..d4f8b297f 100644
--- a/crates/radicle-protocol/src/connections.rs
+++ b/crates/radicle-protocol/src/connections.rs
@@ -8,7 +8,7 @@ pub mod events;
use radicle::node::config::RateLimits;
use radicle::prelude::RepoId;
-use session::{HasAttempts as _, Session, Sessions};
+use session::{HasAttempts as _, Pinged, Session, Sessions};
mod session;
use std::collections::HashSet;
@@ -80,6 +80,10 @@ pub enum CommandEvent {
node: NodeId,
rid: RepoId,
},
+ Pinged {
+ node: NodeId,
+ pinged: Option<Pinged>,
+ },
}
impl Connections {
@@ -90,6 +94,7 @@ impl Connections {
commands::Command::Disconnect(disconnect) => self.disconnected(disconnect),
commands::Command::Subscribe(subscribe) => self.subscribed(subscribe),
commands::Command::SubscribeTo(subscribe) => self.subscribed_to(subscribe),
+ commands::Command::Pong(pong) => self.pinged(pong),
}
}
@@ -150,6 +155,13 @@ impl Connections {
CommandEvent::MissingSession { node }
}
}
+
+ fn pinged(&mut self, commands::Pong { node, pong }: commands::Pong) -> CommandEvent {
+ self.sessions.pinged(&node, pong).map_or_else(
+ |session::Missing| CommandEvent::MissingSession { node },
+ |pinged| CommandEvent::Pinged { node, pinged },
+ )
+ }
}
impl Connections {
diff --git a/crates/radicle-protocol/src/connections/commands.rs b/crates/radicle-protocol/src/connections/commands.rs
index d51681e2e..861f57148 100644
--- a/crates/radicle-protocol/src/connections/commands.rs
+++ b/crates/radicle-protocol/src/connections/commands.rs
@@ -6,12 +6,15 @@ use radicle::{
use crate::service::message;
+use super::session;
+
pub enum Command {
Attempt(Attempt),
Connect(Connect),
Disconnect(Disconnect),
Subscribe(Subscribe),
SubscribeTo(SubscribeTo),
+ Pong(Pong),
}
impl From<Attempt> for Command {
@@ -44,6 +47,12 @@ impl From<SubscribeTo> for Command {
}
}
+impl From<Pong> for Command {
+ fn from(v: Pong) -> Self {
+ Self::Pong(v)
+ }
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Attempt {
pub node: NodeId,
@@ -75,3 +84,9 @@ pub struct SubscribeTo {
pub node: NodeId,
pub rid: RepoId,
}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Pong {
+ pub node: NodeId,
+ pub pong: session::Pong,
+}
diff --git a/crates/radicle-protocol/src/connections/session.rs b/crates/radicle-protocol/src/connections/session.rs
index 64fe9c7e0..977be8341 100644
--- a/crates/radicle-protocol/src/connections/session.rs
+++ b/crates/radicle-protocol/src/connections/session.rs
@@ -6,7 +6,7 @@ use radicle::{
prelude::RepoId,
};
-use crate::service::message;
+use crate::service::{message, ZeroBytes, MAX_LATENCIES};
/// Time after which a connection is considered stable.
#[allow(unused)]
@@ -55,6 +55,9 @@ impl HasAttempts for State {
}
}
+/// Marker type for when a [`NodeId`] is missing from [`Sessions`].
+pub struct Missing;
+
pub struct Sessions {
initial: HashMap<NodeId, Session<Initial>>,
attempted: HashMap<NodeId, Session<Attempted>>,
@@ -251,6 +254,11 @@ impl Sessions {
false
}
+ pub fn pinged(&mut self, node: &NodeId, pong: Pong) -> Result<Option<Pinged>, Missing> {
+ let session = self.connected.get_mut(node).ok_or(Missing)?;
+ Ok(session.pinged(pong))
+ }
+
fn remove_session(&mut self, node: &NodeId) -> Option<Session<State>> {
self.initial
.remove(node)
@@ -537,9 +545,21 @@ impl Connected {
}
}
+#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Ping {
- since: LocalTime,
- rng: fastrand::Rng,
+ pub since: LocalTime,
+ pub rng: fastrand::Rng,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Pong {
+ pub now: LocalTime,
+ pub zeroes: ZeroBytes,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Pinged {
+ pub latency: LocalDuration,
}
impl Session<Connected> {
@@ -570,6 +590,27 @@ impl Session<Connected> {
msg
}
+ pub fn pinged(&mut self, Pong { zeroes, now }: Pong) -> Option<Pinged> {
+ if let PingState::AwaitingResponse {
+ len: ponglen,
+ since,
+ } = self.state.ping
+ {
+ if (ponglen as usize) == zeroes.len() {
+ self.state.ping = PingState::Ok;
+ let latency = now - since;
+ self.state.latencies.push_back(latency);
+ // TODO(finto): MAX_LATENCIES should likely be configured
+ // somewhere else
+ if self.state.latencies.len() > MAX_LATENCIES {
+ self.state.latencies.pop_front();
+ }
+ return Some(Pinged { latency });
+ }
+ }
+ None
+ }
+
pub fn idle(&mut self, now: LocalTime, stable_threshold: LocalDuration) {
let Connected {
since,
commit db6337e73043b1ef35e28548ee556d566cf5fda0
Author: Fintan Halpenny <fintan.halpenny@gmail.com>
Date: Wed Aug 13 15:50:40 2025 +0100
protocol: connections subscribe commands
Add commands for mutating the subscription of a peer session.
One is intended for setting the subscription, expected to be used when
a subscription message is announced as a gossip message.
The other is inserting an RID into its filter set, expected to be used
when a gossip message from the node gives us information that this
node is interested in the given RID, e.g. refs announcements,
inventory announcements.
diff --git a/crates/radicle-protocol/src/connections.rs b/crates/radicle-protocol/src/connections.rs
index b38651ce7..dce945c4d 100644
--- a/crates/radicle-protocol/src/connections.rs
+++ b/crates/radicle-protocol/src/connections.rs
@@ -7,6 +7,7 @@ pub mod effects;
pub mod events;
use radicle::node::config::RateLimits;
+use radicle::prelude::RepoId;
use session::{HasAttempts as _, Session, Sessions};
mod session;
@@ -18,7 +19,7 @@ use radicle::node::address;
use radicle::node::{Address, HostName, Link, NodeId, Severity};
use crate::service::limiter::RateLimiter;
-use crate::service::DisconnectReason;
+use crate::service::{message, DisconnectReason};
/// Minimum amount of time to wait before reconnecting to a peer.
pub const MIN_RECONNECTION_DELTA: LocalDuration = LocalDuration::from_secs(3);
@@ -65,10 +66,20 @@ impl Default for ReconnectionDelay {
}
pub enum CommandEvent {
- MissingSession { node: NodeId },
+ MissingSession {
+ node: NodeId,
+ },
Attempted(Session<session::Attempted>),
Connected(Session<session::Connected>),
Disconnected(Session<session::Disconnected>),
+ Subscribed {
+ node: NodeId,
+ subscription: message::Subscribe,
+ },
+ SubscribedTo {
+ node: NodeId,
+ rid: RepoId,
+ },
}
impl Connections {
@@ -77,6 +88,8 @@ impl Connections {
commands::Command::Attempt(attempt) => self.attempted(attempt),
commands::Command::Connect(connect) => self.connected(connect),
commands::Command::Disconnect(disconnect) => self.disconnected(disconnect),
+ commands::Command::Subscribe(subscribe) => self.subscribed(subscribe),
+ commands::Command::SubscribeTo(subscribe) => self.subscribed_to(subscribe),
}
}
@@ -115,6 +128,28 @@ impl Connections {
.map(CommandEvent::Disconnected)
.unwrap_or(CommandEvent::MissingSession { node })
}
+
+ fn subscribed(
+ &mut self,
+ commands::Subscribe { node, subscription }: commands::Subscribe,
+ ) -> CommandEvent {
+ if self.sessions.subscribe(&node, subscription.clone()) {
+ CommandEvent::Subscribed { node, subscription }
+ } else {
+ CommandEvent::MissingSession { node }
+ }
+ }
+
+ fn subscribed_to(
+ &mut self,
+ commands::SubscribeTo { node, rid }: commands::SubscribeTo,
+ ) -> CommandEvent {
+ if self.sessions.subscribe_to(&node, &rid) {
+ CommandEvent::SubscribedTo { node, rid }
+ } else {
+ CommandEvent::MissingSession { node }
+ }
+ }
}
impl Connections {
diff --git a/crates/radicle-protocol/src/connections/commands.rs b/crates/radicle-protocol/src/connections/commands.rs
index a7bdad615..d51681e2e 100644
--- a/crates/radicle-protocol/src/connections/commands.rs
+++ b/crates/radicle-protocol/src/connections/commands.rs
@@ -1,10 +1,17 @@
use localtime::LocalTime;
-use radicle::node::{Link, NodeId};
+use radicle::{
+ node::{Link, NodeId},
+ prelude::RepoId,
+};
+
+use crate::service::message;
pub enum Command {
Attempt(Attempt),
Connect(Connect),
Disconnect(Disconnect),
+ Subscribe(Subscribe),
+ SubscribeTo(SubscribeTo),
}
impl From<Attempt> for Command {
@@ -25,6 +32,18 @@ impl From<Disconnect> for Command {
}
}
+impl From<Subscribe> for Command {
+ fn from(v: Subscribe) -> Self {
+ Self::Subscribe(v)
+ }
+}
+
+impl From<SubscribeTo> for Command {
+ fn from(v: SubscribeTo) -> Self {
+ Self::SubscribeTo(v)
+ }
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Attempt {
pub node: NodeId,
@@ -44,3 +63,15 @@ pub struct Disconnect {
pub since: LocalTime,
pub retry_at: Option<LocalTime>,
}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Subscribe {
+ pub node: NodeId,
+ pub subscription: message::Subscribe,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct SubscribeTo {
+ pub node: NodeId,
+ pub rid: RepoId,
+}
diff --git a/crates/radicle-protocol/src/connections/session.rs b/crates/radicle-protocol/src/connections/session.rs
index b04449ef6..64fe9c7e0 100644
--- a/crates/radicle-protocol/src/connections/session.rs
+++ b/crates/radicle-protocol/src/connections/session.rs
@@ -203,6 +203,54 @@ impl Sessions {
})
}
+ pub fn subscribe(&mut self, node: &NodeId, subscription: message::Subscribe) -> bool {
+ if let Some(session) = self.connected.get_mut(node) {
+ session.set_subscription(subscription);
+ return true;
+ }
+
+ if let Some(session) = self.disconnected.get_mut(node) {
+ session.set_subscription(subscription);
+ return true;
+ }
+
+ if let Some(session) = self.attempted.get_mut(node) {
+ session.set_subscription(subscription);
+ return true;
+ }
+
+ if let Some(session) = self.initial.get_mut(node) {
+ session.set_subscription(subscription);
+ return true;
+ }
+
+ false
+ }
+
+ pub fn subscribe_to(&mut self, node: &NodeId, rid: &RepoId) -> bool {
+ if let Some(session) = self.connected.get_mut(node) {
+ session.subscribe_to(rid);
+ return true;
+ }
+
+ if let Some(session) = self.disconnected.get_mut(node) {
+ session.subscribe_to(rid);
+ return true;
+ }
+
+ if let Some(session) = self.attempted.get_mut(node) {
+ session.subscribe_to(rid);
+ return true;
+ }
+
+ if let Some(session) = self.initial.get_mut(node) {
+ session.subscribe_to(rid);
+ return true;
+ }
+
+ false
+ }
+
fn remove_session(&mut self, node: &NodeId) -> Option<Session<State>> {
self.initial
.remove(node)
commit 1fde061794ea4dddb8beb8a3949c19bfcd3ab8c5
Author: Fintan Halpenny <fintan.halpenny@gmail.com>
Date: Wed Aug 13 12:42:11 2025 +0100
protocol: node events
The protocol will often want to emit node events so that a subscriber
can listen to these events and act upon them – for example, the
Radicle CI code uses this to decide when to start CI jobs.
The sans I/O approach here is a simple queue where events can be
pushed, popped, or drained.
An `Emitter` trait is provisionally defined to show that these events
should be emitted from a producer to some subscriber or subscribers.
diff --git a/crates/radicle-protocol/src/lib.rs b/crates/radicle-protocol/src/lib.rs
index 8934ff45f..37cdbc486 100644
--- a/crates/radicle-protocol/src/lib.rs
+++ b/crates/radicle-protocol/src/lib.rs
@@ -6,6 +6,7 @@ pub mod worker;
pub mod connections;
pub mod fetcher;
+pub mod node;
pub mod tasks;
/// Peer-to-peer protocol version.
diff --git a/crates/radicle-protocol/src/node.rs b/crates/radicle-protocol/src/node.rs
new file mode 100644
index 000000000..a9970c28f
--- /dev/null
+++ b/crates/radicle-protocol/src/node.rs
@@ -0,0 +1 @@
+pub mod events;
diff --git a/crates/radicle-protocol/src/node/events.rs b/crates/radicle-protocol/src/node/events.rs
new file mode 100644
index 000000000..5560475c2
--- /dev/null
+++ b/crates/radicle-protocol/src/node/events.rs
@@ -0,0 +1,48 @@
+pub mod emitter;
+
+use std::collections::VecDeque;
+
+use radicle::node::Event;
+
+/// Keep track of [`Event`]s that occur within the rest of the protocol system.
+///
+/// The events are queued with [`NodeEvents::push_event`] and removed using
+/// [`NodeEvents::pop_event`] and [`NodeEvents::drain_events`].
+///
+/// To inspect the events use [`NodeEvents::events`].
+pub struct Events {
+ events: VecDeque<Event>,
+}
+
+impl Extend<Event> for Events {
+ fn extend<T: IntoIterator<Item = Event>>(&mut self, iter: T) {
+ self.events.extend(iter);
+ }
+}
+
+impl Events {
+ /// Push an [`Event`] onto the events queue.
+ pub fn push_event(&mut self, event: Event) {
+ self.events.push_back(event);
+ }
+
+ /// Pop the next [`Event`] from the events queue.
+ pub fn pop_event(&mut self) -> Option<Event> {
+ self.events.pop_front()
+ }
+
+ /// Drain the queue of all its events.
+ ///
+ /// This is useful for batch processing the available events.
+ pub fn drain_events(&mut self) -> impl Iterator<Item = Event> + '_ {
+ self.events.drain(0..self.events.len())
+ }
+}
+
+impl Events {
+ /// Get the events that are in the queue currently, without modifying the
+ /// queue itself.
+ pub fn events(&self) -> impl Iterator<Item = &Event> {
+ self.events.iter()
+ }
+}
diff --git a/crates/radicle-protocol/src/node/events/emitter.rs b/crates/radicle-protocol/src/node/events/emitter.rs
new file mode 100644
index 000000000..119e3f417
--- /dev/null
+++ b/crates/radicle-protocol/src/node/events/emitter.rs
@@ -0,0 +1,26 @@
+//! An [`Emitter`] captures the ability to emit [`Event`]s to some subscriber
+//! mechanism.
+
+use radicle::node::Event;
+
+use super::Events;
+
+/// The ability of emit an event to some subscriber mechanism.
+pub trait Emitter {
+ /// Emit a single [`Event`], bypassing the need of an events queue.
+ fn emit(&self, event: Event);
+
+ /// Emit the next event from the events queue.
+ fn emit_next(&self, events: &mut Events) {
+ if let Some(event) = events.pop_event() {
+ self.emit(event);
+ }
+ }
+
+ /// Emit all the events that are currently on the queue.
+ fn emit_all(&self, events: &mut Events) {
+ for event in events.drain_events() {
+ self.emit(event);
+ }
+ }
+}
commit 990c52accf82f248dfa5c59724bc4208358431bb
Author: Fintan Halpenny <fintan.halpenny@gmail.com>
Date: Fri Aug 8 13:13:04 2025 +0100
protocol: fetch state
Similar to previous efforts, this change takes the fetching slice of the
`Service` and attempts to capture a sans-IO implementation of it.
It essentially translates `Service::fetch` into the `FetchState` machine. What's
important to note here is that it does not entangle the idea of sessions with
the idea of fetching. The state is purely based on `NodeId`s and `RepoId`s.
Note here that a layer above would make sure that connected sessions, using the
`Connections` state, would perform fetches and using `FetchState`.
diff --git a/crates/radicle-protocol/src/fetcher.rs b/crates/radicle-protocol/src/fetcher.rs
new file mode 100644
index 000000000..fba0ea843
--- /dev/null
+++ b/crates/radicle-protocol/src/fetcher.rs
@@ -0,0 +1,519 @@
+pub mod commands;
+pub use commands::Command;
+pub mod effects;
+pub mod events;
+
+use std::collections::{BTreeMap, HashSet, VecDeque};
+use std::time;
+
+use nonempty::NonEmpty;
+
+use radicle::identity::DocAt;
+use radicle::node;
+use radicle::node::NodeId;
+use radicle::prelude::RepoId;
+use radicle::storage::{refs::RefsAt, RefUpdate};
+
+// TODO(finto): I think this should be defined here, and the worker should
+// provide the result based on this.
+type WorkerResult = Result<Fetched, crate::worker::FetchError>;
+
+// TODO(finto): `Service::fetch_refs_at` and the use of `refs_status_of` is a
+// layer above the `Fetcher` where it would perform I/O, mocked out by a trait,
+// to check if there are wants and add a fetch to the Fetcher.
+
+/// Maximum items in the fetch queue.
+pub const MAX_FETCH_QUEUE_SIZE: usize = 128;
+
+/// Maintain the state of ongoing and queued fetches.
+pub struct FetcherState {
+ fetching: BTreeMap<NodeId, Fetching>,
+ queues: BTreeMap<NodeId, Queue>,
+ config: Config,
+}
+
+impl FetcherState {
+ /// Transition the state of ongoing fetches by recording new fetches that
+ /// are occurring, queuing them is the node if required, attempting to
+ /// dequeue fetches, and marking fetches as complete.
+ pub fn handle_command(&mut self, command: Command) -> Vec<Command> {
+ match command {
+ Command::Fetch(fetch) => self.handle_fetch(fetch),
+ Command::Fetched(fetched) => self.handle_fetched(fetched),
+ }
+ }
+
+ fn handle_fetch(&mut self, fetch: commands::Fetch) -> Vec<Command> {
+ let mut commands = Vec::new();
+ match fetch {
+ commands::Fetch::Repository { from, rid, .. } => {
+ let fetching = self.fetching.entry(from).or_default();
+ fetching.fetching(
+ rid,
+ FetchingFor {
+ from,
+ refs_at: vec![],
+ },
+ );
+ }
+ commands::Fetch::RefsAt {
+ from, rid, refs_at, ..
+ } => {
+ let fetching = self.fetching.entry(from).or_default();
+ fetching.fetching(
+ rid,
+ FetchingFor {
+ from,
+ refs_at: refs_at.into(),
+ },
+ );
+ }
+ commands::Fetch::Queue {
+ from,
+ rid,
+ refs_at,
+ timeout,
+ } => {
+ let queue = self
+ .queues
+ .entry(from)
+ .or_insert(Queue::new(self.config.maximum_queue_size));
+ match queue.enqueue(QueuedFetch {
+ rid,
+ from,
+ refs_at,
+ timeout,
+ }) {
+ Enqueue::CapacityReached(queued_fetch) => {
+ commands.push(commands::Fetch::from(queued_fetch).into());
+ }
+ Enqueue::Duplicate(queued_fetch) => {
+ commands.push(commands::Fetch::from(queued_fetch).into());
+ }
+ Enqueue::Queued => { /* TODO(finto): I think we also want to return events */ }
+ }
+ }
+ }
+ commands
+ }
+
+ fn handle_fetched(&mut self, fetched: commands::Fetched) -> Vec<Command> {
+ let mut commands = Vec::new();
+ match fetched {
+ commands::Fetched::DequeueFetches => {
+ self.deuque_fetches(&mut commands);
+ commands
+ }
+ commands::Fetched::Fetched { from, rid } => {
+ self.fetched_from(&from, &rid);
+ vec![]
+ }
+ }
+ }
+
+ fn deuque_fetches(&mut self, commands: &mut Vec<Command>) {
+ for queue in self.queues.values_mut() {
+ if let Some(QueuedFetch {
+ rid,
+ from,
+ refs_at,
+ timeout,
+ }) = queue.dequeue()
+ {
+ let command = NonEmpty::from_vec(refs_at).map_or(
+ commands::Fetch::Repository { from, rid, timeout },
+ |refs_at| commands::Fetch::RefsAt {
+ from,
+ rid,
+ refs_at,
+ timeout,
+ },
+ );
+ commands.push(command.into());
+ }
+ }
+ }
+
+ fn fetched_from(&mut self, node: &NodeId, rid: &RepoId) -> Option<FetchingFor> {
+ let fetching = self.fetching.get_mut(node)?;
+ fetching.fetched(rid)
+ }
+}
+
+impl FetcherState {
+ /// The protocol wishes to fetch the [`RepoId`] from the given [`NodeId`],
+ /// with the specified set of [`RefsAt`].
+ ///
+ /// This will result in a [`FetchResult`], reporting back to the protocol
+ /// what events occurred, which effects should performed, and the commands
+ /// to transition the state using [`FetchState::handle_command`].
+ pub fn fetch(
+ &self,
+ rid: RepoId,
+ from: NodeId,
+ refs_at: Vec<RefsAt>,
+ timeout: time::Duration,
+ ) -> FetchResult {
+ let mut result = FetchResult::default();
+ if let Some(fetching) = self.is_fetching(&from, &rid) {
+ result.queue_fetch(rid, from, refs_at, timeout);
+ result.already_fetching(rid, fetching.clone());
+ return result;
+ }
+
+ if self.is_at_capacity(&from) {
+ result.queue_fetch(rid, from, refs_at, timeout);
+ result.capacity_reached();
+ return result;
+ }
+
+ match NonEmpty::from_vec(refs_at) {
+ Some(refs_at) => result.fetch_refs_at(from, rid, refs_at, timeout),
+ None => result.fetch_repository(from, rid, timeout),
+ }
+ result
+ }
+
+ /// The protocol wishes to mark the fetch for [`RepoId`] from the given
+ /// [`NodeId`] as done, with the specified [`WorkerResult`].
+ ///
+ /// This will result in a [`FetchedResult`], reporting back to the protocol
+ /// what events occurred, which effects should performed, and the commands
+ /// to transition the state using [`FetchState::handle_command`].
+ pub fn fetched(&self, from: NodeId, rid: RepoId, worker_result: WorkerResult) -> FetchedResult {
+ let mut result = FetchedResult::default();
+ if self.is_fetching(&from, &rid).is_none() {
+ result.unexpected(from, rid);
+ return result;
+ };
+ match worker_result {
+ Ok(success) => {
+ if success.clone && success.doc.is_public() {
+ result.public_repo(rid);
+ }
+ if !success.updated.is_empty() && !success.updated.iter().all(|u| u.is_skipped()) {
+ result.announce(rid, success.doc, success.namespaces.clone());
+ }
+ result.refs_fetched(from, rid, success.updated.clone());
+ let node_result = node::FetchResult::Success {
+ updated: success.updated,
+ namespaces: success.namespaces,
+ clone: success.clone,
+ };
+ result.notify(from, rid, node_result);
+ }
+ Err(e) => {
+ if e.is_timeout() {
+ result.disconnect(from, e.to_string());
+ }
+ let node_result = node::FetchResult::Failed {
+ reason: e.to_string(),
+ };
+ result.notify(from, rid, node_result);
+ }
+ };
+
+ result.dequeue_fetches();
+ result
+ }
+
+ /// Get the [`FetchingFor`] for the provided [`NodeId`] and [`RepoId`],
+ /// returning `None` if it does not exist.
+ fn is_fetching(&self, node: &NodeId, rid: &RepoId) -> Option<&FetchingFor> {
+ self.fetching.get(node).and_then(|f| f.is_fetching(rid))
+ }
+
+ /// Check if the number of fetches exceeds the maximum number of concurrent
+ /// fetches for a given [`NodeId`].
+ fn is_at_capacity(&self, node: &NodeId) -> bool {
+ let number_of_fetches = self.fetching.get(node).map_or(0, |f| f.number_of_fetches());
+ number_of_fetches > self.config.maximum_concurrency
+ }
+}
+
+/// Configuration for the [`FetchState`].
+pub struct Config {
+ /// Maximum number of concurrent fetches per peer connection.
+ maximum_concurrency: usize,
+ /// Maximum fetching queue size for a single node.
+ maximum_queue_size: MaxQueueSize,
+}
+
+/// Fetch state for an ongoing fetch.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct FetchingFor {
+ /// Node we're fetching from.
+ from: NodeId,
+ /// What refs we're fetching.
+ refs_at: Vec<RefsAt>,
+}
+
+impl FetchingFor {
+ pub fn new(from: NodeId, refs_at: Vec<RefsAt>) -> Self {
+ Self { from, refs_at }
+ }
+}
+
+/// Keep track of which repositories are being fetched, and which node and
+/// `rad/sigrefs` they are fetching.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+struct Fetching {
+ inner: BTreeMap<RepoId, FetchingFor>,
+}
+
+impl Fetching {
+ /// Get the number of fetches currently happening.
+ fn number_of_fetches(&self) -> usize {
+ self.inner.len()
+ }
+
+ /// Inspect the [`FetchingFor`] of the [`RepoId`].
+ fn is_fetching(&self, rid: &RepoId) -> Option<&FetchingFor> {
+ self.inner.get(rid)
+ }
+
+ /// The [`RepoId`] is currently being fetched.
+ fn fetching(&mut self, rid: RepoId, state: FetchingFor) {
+ self.inner.insert(rid, state);
+ }
+
+ /// The [`RepoId`] has been fetched.
+ fn fetched(&mut self, rid: &RepoId) -> Option<FetchingFor> {
+ self.inner.remove(rid)
+ }
+}
+
+/// Fetch waiting to be processed, in the fetch queue.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct QueuedFetch {
+ /// Repo being fetched.
+ pub rid: RepoId,
+ /// Peer being fetched from.
+ pub from: NodeId,
+ /// Refs being fetched.
+ pub refs_at: Vec<RefsAt>,
+ /// The timeout given for the fetch request.
+ pub timeout: time::Duration,
+}
+
+impl From<QueuedFetch> for commands::Fetch {
+ fn from(
+ QueuedFetch {
+ rid,
+ from,
+ refs_at,
+ timeout,
+ }: QueuedFetch,
+ ) -> Self {
+ Self::Queue {
+ from,
+ rid,
+ refs_at,
+ timeout,
+ }
+ }
+}
+
+/// A queue for keeping track of fetches.
+///
+/// It ensures that the queue contains unique items for fetching, and does not
+/// exceed the provided maximum capacity.
+struct Queue {
+ queue: VecDeque<QueuedFetch>,
+ max_queue_size: MaxQueueSize,
+}
+
+/// The maximum number of fetches that can be queued for a single node.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
+pub struct MaxQueueSize(usize);
+
+impl MaxQueueSize {
+ /// Checks if the `n` provided exceeds the maximum queue size.
+ fn is_exceeded_by(&self, n: usize) -> bool {
+ n >= self.0
+ }
+}
+
+impl Default for MaxQueueSize {
+ fn default() -> Self {
+ Self(MAX_FETCH_QUEUE_SIZE)
+ }
+}
+
+/// The result of [`Queue::enqueue`].
+pub enum Enqueue {
+ /// The capacity of the queue has been exceeded, and the [`QueuedFetch`] is
+ /// returned.
+ CapacityReached(QueuedFetch),
+ /// The [`QueuedFetch`] was a duplicate.
+ Duplicate(QueuedFetch),
+ /// The [`QueuedFetch`] was successfully queued.
+ Queued,
+}
+
+impl Queue {
+ /// Create the [`Queue`] with the given [`MaxQueueSize`].
+ fn new(max_queue_size: MaxQueueSize) -> Self {
+ Self {
+ queue: VecDeque::with_capacity(max_queue_size.0),
+ max_queue_size,
+ }
+ }
+
+ /// Enqueues a fetch onto the back of the queue, and will only succeed if
+ /// the queue has not reached capacity and if the item is unique.
+ fn enqueue(&mut self, fetch: QueuedFetch) -> Enqueue {
+ if self.max_queue_size.is_exceeded_by(self.queue.len()) {
+ Enqueue::CapacityReached(fetch)
+ } else if self.queue.contains(&fetch) {
+ Enqueue::Duplicate(fetch)
+ } else {
+ self.queue.push_back(fetch);
+ Enqueue::Queued
+ }
+ }
+
+ /// Dequeues a fetch from the front of the queue.
+ fn dequeue(&mut self) -> Option<QueuedFetch> {
+ self.queue.pop_front()
+ }
+}
+
+/// Events, effects, and commands that occur from [`FetchState::fetch`].
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct FetchResult {
+ /// Events that can be recorded by the rest of the system.
+ pub events: Vec<events::Fetch>,
+ /// Commands to progress [`FetchState`].
+ pub commands: Vec<commands::Fetch>,
+}
+
+impl FetchResult {
+ fn capacity_reached(&mut self) {
+ self.events.push(events::Fetch::CapacityReached);
+ }
+
+ fn already_fetching(&mut self, rid: RepoId, fetching: FetchingFor) {
+ self.events
+ .push(events::Fetch::AlreadyFetching { rid, fetching });
+ }
+
+ fn fetch_repository(&mut self, from: NodeId, rid: RepoId, timeout: time::Duration) {
+ self.commands
+ .push(commands::Fetch::Repository { from, rid, timeout });
+ }
+
+ fn fetch_refs_at(
+ &mut self,
+ from: NodeId,
+ rid: RepoId,
+ refs_at: NonEmpty<RefsAt>,
+ timeout: time::Duration,
+ ) {
+ self.commands.push(commands::Fetch::RefsAt {
+ from,
+ rid,
+ refs_at,
+ timeout,
+ });
+ }
+
+ fn queue_fetch(
+ &mut self,
+ rid: RepoId,
+ from: NodeId,
+ refs_at: Vec<RefsAt>,
+ timeout: time::Duration,
+ ) {
+ self.commands.push(commands::Fetch::Queue {
+ rid,
+ from,
+ refs_at,
+ timeout,
+ });
+ }
+}
+
+/// Events, effects, and commands that occur from [`FetchState::fetched`].
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct FetchedResult {
+ /// Events that can be recorded by the rest of the system.
+ pub events: Vec<events::Fetched>,
+ /// Commands to progress [`FetchState`].
+ pub effects: Vec<effects::Fetched>,
+ /// Effects that can be performed by the rest of the system.
+ pub commands: Vec<commands::Fetched>,
+}
+
+impl FetchedResult {
+ fn unexpected(&mut self, node: NodeId, rid: RepoId) {
+ self.events
+ .push(events::Fetched::UnexpectedResult { node, rid });
+ }
+
+ fn notify(&mut self, from: NodeId, rid: RepoId, result: node::FetchResult) {
+ self.effects
+ .push(effects::Fetched::Notify { from, rid, result })
+ }
+
+ fn dequeue_fetches(&mut self) {
+ self.commands.push(commands::Fetched::DequeueFetches);
+ }
+
+ fn disconnect(&mut self, node: NodeId, reason: String) {
+ self.effects
+ .push(effects::Fetched::Disconnect { node, reason })
+ }
+
+ fn announce(&mut self, rid: RepoId, doc: DocAt, namespaces: HashSet<NodeId>) {
+ self.effects.push(effects::Fetched::Announce {
+ rid,
+ doc,
+ namespaces,
+ })
+ }
+
+ fn public_repo(&mut self, rid: RepoId) {
+ self.events.push(events::Fetched::PublicRepo { rid });
+ }
+
+ fn refs_fetched(&mut self, node: NodeId, rid: RepoId, updated: Vec<RefUpdate>) {
+ self.events
+ .push(events::Fetched::RefsFetched { node, rid, updated });
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct Fetched {
+ /// The set of updated references.
+ pub updated: Vec<RefUpdate>,
+ /// The set of remote namespaces that were updated.
+ pub namespaces: HashSet<NodeId>,
+ /// The fetch was a full clone.
+ pub clone: bool,
+ /// Identity doc of fetched repository.
+ pub doc: DocAt,
+}
+
+impl Fetched {
+ pub fn new(doc: DocAt) -> Self {
+ Self {
+ updated: vec![],
+ namespaces: HashSet::new(),
+ clone: false,
+ doc,
+ }
+ }
+}
+
+#[cfg(any(test, feature = "test"))]
+impl qcheck::Arbitrary for Fetched {
+ fn arbitrary(g: &mut qcheck::Gen) -> Self {
+ Fetched {
+ updated: vec![],
+ namespaces: HashSet::arbitrary(g),
+ clone: bool::arbitrary(g),
+ doc: DocAt::arbitrary(g),
+ }
+ }
+}
diff --git a/crates/radicle-protocol/src/fetcher/commands.rs b/crates/radicle-protocol/src/fetcher/commands.rs
new file mode 100644
index 000000000..19f352a74
--- /dev/null
+++ b/crates/radicle-protocol/src/fetcher/commands.rs
@@ -0,0 +1,58 @@
+use std::time;
+
+use nonempty::NonEmpty;
+use radicle::{node::NodeId, prelude::RepoId, storage::refs::RefsAt};
+
+/// Commands for transitioning the [`FetchState`].
+///
+/// [`FetchState`]: super::FetchState
+pub enum Command {
+ Fetch(Fetch),
+ Fetched(Fetched),
+}
+
+impl From<Fetch> for Command {
+ fn from(v: Fetch) -> Self {
+ Self::Fetch(v)
+ }
+}
+
+impl From<Fetched> for Command {
+ fn from(v: Fetched) -> Self {
+ Self::Fetched(v)
+ }
+}
+
+/// Command results that occur when a repository is being fetched.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Fetch {
+ /// The repository should be queued for fetching.
+ Queue {
+ from: NodeId,
+ rid: RepoId,
+ refs_at: Vec<RefsAt>,
+ timeout: time::Duration,
+ },
+ /// The repository should be fetched, and we do not know the references that
+ /// are required for fetching.
+ Repository {
+ from: NodeId,
+ rid: RepoId,
+ timeout: time::Duration,
+ },
+ /// The repository should be fetched, and only the references stated should
+ /// be fetched.
+ RefsAt {
+ from: NodeId,
+ rid: RepoId,
+ refs_at: NonEmpty<RefsAt>,
+ timeout: time::Duration,
+ },
+}
+
+/// Command results that occur after a repository has been fetched.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Fetched {
+ DequeueFetches,
+ Fetched { from: NodeId, rid: RepoId },
+}
diff --git a/crates/radicle-protocol/src/fetcher/effects.rs b/crates/radicle-protocol/src/fetcher/effects.rs
new file mode 100644
index 000000000..11d06336b
--- /dev/null
+++ b/crates/radicle-protocol/src/fetcher/effects.rs
@@ -0,0 +1,28 @@
+use std::collections::HashSet;
+
+use radicle::{identity::DocAt, node, node::NodeId, prelude::RepoId};
+
+/// Effects that should be performed after a repository has been fetched.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Fetched {
+ /// Announce that the namespaces were fetched for this repository.
+ Announce {
+ rid: RepoId,
+ doc: DocAt,
+ namespaces: HashSet<NodeId>,
+ },
+ /// Notify listeners about the result of the fetch.
+ Notify {
+ from: NodeId,
+ rid: RepoId,
+ result: node::FetchResult,
+ },
+ /// The fetch failed, due to a timeout, so the [`NodeId`] should likely be
+ /// disconnected.
+ Disconnect {
+ node: NodeId,
+ // TODO(finto): this was a FetchError type is it ok to have it just as a
+ // String?
+ reason: String,
+ },
+}
diff --git a/crates/radicle-protocol/src/fetcher/events.rs b/crates/radicle-protocol/src/fetcher/events.rs
new file mode 100644
index 000000000..2b71b0a46
--- /dev/null
+++ b/crates/radicle-protocol/src/fetcher/events.rs
@@ -0,0 +1,30 @@
+use radicle::{node::NodeId, prelude::RepoId, storage::RefUpdate};
+
+use super::FetchingFor;
+
+/// Events that occur when a repository is being fetched.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Fetch {
+ /// The repository is already being fetched.
+ AlreadyFetching { rid: RepoId, fetching: FetchingFor },
+ /// The capacity of the node has been reached.
+ CapacityReached,
+}
+
+/// Events that occur after a repository has been fetched.
+// TODO(finto): note to self a successful fetch should mark a seed as discovered
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Fetched {
+ /// There was no ongoing fetch for the given [`NodeId`] and [`RepoId`].
+ UnexpectedResult { node: NodeId, rid: RepoId },
+ /// The [`RepoId`] was fetched from the [`NodeId`] with the set of updated
+ /// references.
+ RefsFetched {
+ node: NodeId,
+ rid: RepoId,
+ updated: Vec<RefUpdate>,
+ },
+ // TODO(finto): this needs to be used to add inventory
+ /// The fetched repository was a public repository.
+ PublicRepo { rid: RepoId },
+}
diff --git a/crates/radicle-protocol/src/lib.rs b/crates/radicle-protocol/src/lib.rs
index a54b764c1..8934ff45f 100644
--- a/crates/radicle-protocol/src/lib.rs
+++ b/crates/radicle-protocol/src/lib.rs
@@ -5,6 +5,7 @@ pub mod wire;
pub mod worker;
pub mod connections;
+pub mod fetcher;
pub mod tasks;
/// Peer-to-peer protocol version.
diff --git a/crates/radicle/src/node.rs b/crates/radicle/src/node.rs
index 8753d9e9d..ec1ad2c93 100644
--- a/crates/radicle/src/node.rs
+++ b/crates/radicle/src/node.rs
@@ -898,7 +898,7 @@ impl From<Vec<Seed>> for Seeds {
}
}
-#[derive(Clone, Debug, Serialize, Deserialize)]
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "status", rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum FetchResult {
commit a2c0d12fa32b1e3eda9f8078b84e979953b10226
Author: Fintan Halpenny <fintan.halpenny@gmail.com>
Date: Wed Jul 2 10:36:43 2025 +0100
protocol: peer connections
An event/command approach to keeping track of peer connections.
The `session` module keeps track of the state of different peer sessions in
several maps. It keeps them separated by the state that they're in and ensures
that the correct type of session is used using a generic type.
These sessions are then kept track of in a `Connections` state machine, that
performs the checks of what should happen in the state machine, `commands`, and
output useful `events`, and `effects` that can be observed by the rest of the
protocol.
diff --git a/crates/radicle-protocol/src/connections.rs b/crates/radicle-protocol/src/connections.rs
new file mode 100644
index 000000000..b38651ce7
--- /dev/null
+++ b/crates/radicle-protocol/src/connections.rs
@@ -0,0 +1,399 @@
+// TODO(finto): command should be something else, perhaps `input`?
+pub mod command;
+pub use command::{Connect, Disconnect};
+
+pub mod commands;
+pub mod effects;
+pub mod events;
+
+use radicle::node::config::RateLimits;
+use session::{HasAttempts as _, Session, Sessions};
+mod session;
+
+use std::collections::HashSet;
+use std::net::IpAddr;
+
+use localtime::{LocalDuration, LocalTime};
+use radicle::node::address;
+use radicle::node::{Address, HostName, Link, NodeId, Severity};
+
+use crate::service::limiter::RateLimiter;
+use crate::service::DisconnectReason;
+
+/// Minimum amount of time to wait before reconnecting to a peer.
+pub const MIN_RECONNECTION_DELTA: LocalDuration = LocalDuration::from_secs(3);
+/// Maximum amount of time to wait before reconnecting to a peer.
+pub const MAX_RECONNECTION_DELTA: LocalDuration = LocalDuration::from_mins(60);
+
+pub struct Connections {
+ /// The state of the connection lifecycle for each node in the network.
+ sessions: Sessions,
+ /// Keep track of which node connections are meant to be persistent.
+ persistent: HashSet<NodeId>,
+ /// Keep track of banned IP addresses.
+ banned: HashSet<IpAddr>,
+ /// Rate limiter of IP hosts.
+ limiter: RateLimiter,
+ /// Configuration for managing connections.
+ config: Config,
+}
+
+pub struct Config {
+ /// Duration for a connection to be considered idle.
+ idle: LocalDuration,
+ /// Allowed number of inbound connections
+ inbound_limit: usize,
+ limits: RateLimits,
+ reconnection_delay: ReconnectionDelay,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct ReconnectionDelay {
+ /// The minimum amount of time to wait before attempting a re-connection.
+ pub min_delta: LocalDuration,
+ /// The maximum amount of time to wait before attempting a re-connection.
+ pub max_delta: LocalDuration,
+}
+
+impl Default for ReconnectionDelay {
+ fn default() -> Self {
+ Self {
+ min_delta: MIN_RECONNECTION_DELTA,
+ max_delta: MAX_RECONNECTION_DELTA,
+ }
+ }
+}
+
+pub enum CommandEvent {
+ MissingSession { node: NodeId },
+ Attempted(Session<session::Attempted>),
+ Connected(Session<session::Connected>),
+ Disconnected(Session<session::Disconnected>),
+}
+
+impl Connections {
+ pub fn handle_command(&mut self, command: commands::Command) -> CommandEvent {
+ match command {
+ commands::Command::Attempt(attempt) => self.attempted(attempt),
+ commands::Command::Connect(connect) => self.connected(connect),
+ commands::Command::Disconnect(disconnect) => self.disconnected(disconnect),
+ }
+ }
+
+ fn attempted(&mut self, commands::Attempt { node }: commands::Attempt) -> CommandEvent {
+ self.sessions
+ .session_to_attempted(&node)
+ .map(CommandEvent::Attempted)
+ .unwrap_or(CommandEvent::MissingSession { node })
+ }
+
+ fn connected(
+ &mut self,
+ commands::Connect {
+ node,
+ now,
+ link,
+ persistent,
+ }: commands::Connect,
+ ) -> CommandEvent {
+ self.sessions
+ .session_to_connected(&node, now, link, persistent)
+ .map(CommandEvent::Connected)
+ .unwrap_or(CommandEvent::MissingSession { node })
+ }
+
+ fn disconnected(
+ &mut self,
+ commands::Disconnect {
+ node,
+ since,
+ retry_at,
+ }: commands::Disconnect,
+ ) -> CommandEvent {
+ self.sessions
+ .session_to_disconnected(&node, since, retry_at)
+ .map(CommandEvent::Disconnected)
+ .unwrap_or(CommandEvent::MissingSession { node })
+ }
+}
+
+impl Connections {
+ pub fn sessions(&self) -> &Sessions {
+ &self.sessions
+ }
+
+ pub fn accept(&mut self, ip: IpAddr, now: LocalTime) -> AcceptResult {
+ let mut result = AcceptResult::default();
+ // Always accept localhost connections, even if we already reached
+ // our inbound connection limit.
+ if ip.is_loopback() || ip.is_unspecified() {
+ result.local_host(ip);
+ return result;
+ }
+
+ if self.has_reached_inbound_limit() {
+ result.inbound_limit_exceeded(ip, self.sessions.connected_inbound());
+ return result;
+ }
+
+ if self.is_ip_banned(&ip) {
+ result.ip_banned(ip);
+ return result;
+ }
+
+ if self.has_reached_ip_limit(&ip, now) {
+ result.host_limited(ip);
+ return result;
+ }
+
+ result.accepted(ip);
+ result
+ }
+
+ pub fn connect(&self, connect: Connect) -> ConnectResult {
+ let mut result = ConnectResult::default();
+ match connect {
+ Connect::Inbound(command::Inbound {
+ node,
+ clock,
+ persistent,
+ }) => match self.sessions.get_connected(&node) {
+ Some(session) => result.already_connected(session.clone(), Link::Inbound),
+ None => {
+ result.connect(node, clock, Link::Inbound, persistent);
+ result.send_initial_messages(node, Link::Inbound);
+ }
+ },
+ Connect::Outbound(command::Outbound {
+ node,
+ addr,
+ persistent,
+ clock,
+ }) => match self.sessions.get_connected(&node) {
+ Some(session) => {
+ result.already_connected(session.clone(), Link::Outbound);
+ result.send_initial_messages(node, *session.link());
+ }
+ None => {
+ if let HostName::Ip(ip) = addr.host {
+ if !address::is_local(&ip) {
+ result.record_ip(node, ip, clock);
+ }
+ }
+ result.connect(node, clock, Link::Outbound, persistent);
+ result.send_initial_messages(node, Link::Outbound);
+ }
+ },
+ }
+ result
+ }
+
+ pub fn disconnect(&self, disconnect: Disconnect) -> DisconnectResult {
+ let mut result = DisconnectResult::default();
+ let Disconnect {
+ node,
+ link,
+ reason,
+ since,
+ } = disconnect;
+ let is_persistent = self.is_persistent(&node);
+ let Some(session) = self.sessions.get_session(&node) else {
+ result.already_disconnected(node);
+ return result;
+ };
+ if *session.link() != link {
+ result.link_conflict(node, *session.link(), link);
+ return result;
+ }
+
+ if is_persistent {
+ let delay = self.reconnection_delay(session.attempts().as_u32());
+ let retry_at = since + delay;
+ result.retry_connection(node, since, retry_at);
+ result.disconnect(node, since, Some(retry_at));
+ } else {
+ let severity = self.reason_severity(reason, since);
+ result.record_severity(node, session.address().clone(), severity);
+ result.disconnect(node, since, None);
+ if link.is_outbound() {
+ result.maintain_connnections();
+ }
+ }
+ result
+ }
+
+ fn reason_severity(&self, reason: DisconnectReason, now: LocalTime) -> Severity {
+ match reason {
+ DisconnectReason::Dial(_)
+ | DisconnectReason::Fetch(_)
+ | DisconnectReason::Connection(_) => {
+ if self.is_online(now) {
+ // If we're "online", there's something wrong with this
+ // peer connection specifically.
+ Severity::Medium
+ } else {
+ Severity::Low
+ }
+ }
+ DisconnectReason::Session(e) => e.severity(),
+ DisconnectReason::Command
+ | DisconnectReason::Conflict
+ | DisconnectReason::SelfConnection => Severity::Low,
+ }
+ }
+
+ /// Try to guess whether we're online or not.
+ fn is_online(&self, now: LocalTime) -> bool {
+ self.sessions
+ .connected()
+ .filter(|(_, s)| s.address().is_routable() && *s.last_active() >= now - self.idle())
+ .count()
+ > 0
+ }
+
+ fn idle(&self) -> LocalDuration {
+ self.config.idle
+ }
+
+ fn is_persistent(&self, node: &NodeId) -> bool {
+ self.persistent.contains(node)
+ }
+
+ fn is_ip_banned(&self, ip: &IpAddr) -> bool {
+ self.banned.contains(ip)
+ }
+
+ // TODO: limit is harshing my buzz by taking &mut self here
+ fn has_reached_ip_limit(&mut self, ip: &IpAddr, now: LocalTime) -> bool {
+ let addr = HostName::from(*ip);
+ self.limiter
+ .limit(addr, None, &self.config.limits.inbound, now)
+ }
+
+ fn has_reached_inbound_limit(&self) -> bool {
+ self.sessions.connected_inbound() >= self.config.inbound_limit
+ }
+
+ fn reconnection_delay(&self, attempts: u32) -> LocalDuration {
+ LocalDuration::from_secs(2u64.pow(attempts)).clamp(
+ self.config.reconnection_delay.min_delta,
+ self.config.reconnection_delay.max_delta,
+ )
+ }
+}
+
+#[derive(Debug, Default)]
+pub struct AcceptResult {
+ pub effects: Vec<effects::Accept>,
+ pub events: Vec<events::Accept>,
+}
+
+impl AcceptResult {
+ fn local_host(&mut self, ip: IpAddr) {
+ self.effects.push(effects::Accept::LocalHost { ip });
+ }
+
+ fn inbound_limit_exceeded(&mut self, ip: IpAddr, connected_inbound: usize) {
+ self.events.push(events::Accept::LimitExceeded {
+ ip,
+ current_inbound: connected_inbound,
+ });
+ }
+
+ fn ip_banned(&mut self, ip: IpAddr) {
+ self.events.push(events::Accept::IpBanned { ip })
+ }
+
+ fn host_limited(&mut self, ip: IpAddr) {
+ self.events.push(events::Accept::HostLimited { ip })
+ }
+
+ fn accepted(&mut self, ip: IpAddr) {
+ self.effects.push(effects::Accept::Accepted { ip })
+ }
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct ConnectResult {
+ pub events: Vec<events::Connect>,
+ pub effects: Vec<effects::Connect>,
+ pub commands: Vec<commands::Connect>,
+}
+
+impl ConnectResult {
+ fn already_connected(&mut self, session: Session<session::Connected>, attempted_link: Link) {
+ self.events.push(events::Connect::AlreadyConnected {
+ session,
+ attempted_link,
+ });
+ }
+
+ fn send_initial_messages(&mut self, node: NodeId, link: Link) {
+ self.effects
+ .push(effects::Connect::SendInitialMessages { node, link });
+ }
+
+ fn record_ip(&mut self, node: NodeId, ip: IpAddr, clock: LocalTime) {
+ self.effects
+ .push(effects::Connect::RecordIp { node, ip, clock });
+ }
+
+ fn connect(&mut self, node: NodeId, clock: LocalTime, link: Link, persistent: bool) {
+ self.commands.push(commands::Connect {
+ node,
+ now: clock,
+ link,
+ persistent,
+ });
+ }
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct DisconnectResult {
+ pub events: Vec<events::Disconnect>,
+ pub effects: Vec<effects::Disconnect>,
+ pub commands: Vec<commands::Disconnect>,
+}
+
+impl DisconnectResult {
+ fn already_disconnected(&mut self, node: NodeId) {
+ self.events
+ .push(events::Disconnect::AlreadyDisconnected { node });
+ }
+
+ fn link_conflict(&mut self, node: NodeId, found: Link, expected: Link) {
+ self.events.push(events::Disconnect::LinkConflict {
+ node,
+ found,
+ expected,
+ });
+ }
+
+ fn retry_connection(&mut self, node: NodeId, since: LocalTime, retry_at: LocalTime) {
+ self.effects.push(effects::Disconnect::RetryConnection {
+ node,
+ since,
+ retry_at,
+ });
+ }
+
+ fn maintain_connnections(&mut self) {
+ self.effects.push(effects::Disconnect::MaintainConnections);
+ }
+
+ fn record_severity(&mut self, node: NodeId, address: Address, severity: Severity) {
+ self.effects.push(effects::Disconnect::RecordServerity {
+ node,
+ address,
+ severity,
+ })
+ }
+
+ fn disconnect(&mut self, node: NodeId, since: LocalTime, retry_at: Option<LocalTime>) {
+ self.commands.push(commands::Disconnect {
+ node,
+ since,
+ retry_at,
+ });
+ }
+}
diff --git a/crates/radicle-protocol/src/connections/command.rs b/crates/radicle-protocol/src/connections/command.rs
new file mode 100644
index 000000000..139ccac62
--- /dev/null
+++ b/crates/radicle-protocol/src/connections/command.rs
@@ -0,0 +1,49 @@
+use localtime::LocalTime;
+
+use radicle::node::{Address, Link, NodeId};
+
+use crate::service::DisconnectReason;
+
+pub enum Connect {
+ Inbound(Inbound),
+ Outbound(Outbound),
+}
+
+impl Connect {
+ pub fn inbound(node: NodeId, clock: LocalTime, persistent: bool) -> Self {
+ Self::Inbound(Inbound {
+ node,
+ clock,
+ persistent,
+ })
+ }
+
+ pub fn outbound(node: NodeId, addr: Address, persistent: bool, clock: LocalTime) -> Self {
+ Self::Outbound(Outbound {
+ node,
+ addr,
+ persistent,
+ clock,
+ })
+ }
+}
+
+pub struct Inbound {
+ pub(super) node: NodeId,
+ pub(super) clock: LocalTime,
+ pub(super) persistent: bool,
+}
+
+pub struct Outbound {
+ pub(super) node: NodeId,
+ pub(super) addr: Address,
+ pub(super) persistent: bool,
+ pub(super) clock: LocalTime,
+}
+
+pub struct Disconnect {
+ pub(super) node: NodeId,
+ pub(super) link: Link,
+ pub(super) reason: DisconnectReason,
+ pub(super) since: LocalTime,
+}
diff --git a/crates/radicle-protocol/src/connections/commands.rs b/crates/radicle-protocol/src/connections/commands.rs
new file mode 100644
index 000000000..a7bdad615
--- /dev/null
+++ b/crates/radicle-protocol/src/connections/commands.rs
@@ -0,0 +1,46 @@
+use localtime::LocalTime;
+use radicle::node::{Link, NodeId};
+
+pub enum Command {
+ Attempt(Attempt),
+ Connect(Connect),
+ Disconnect(Disconnect),
+}
+
+impl From<Attempt> for Command {
+ fn from(v: Attempt) -> Self {
+ Self::Attempt(v)
+ }
+}
+
+impl From<Connect> for Command {
+ fn from(v: Connect) -> Self {
+ Self::Connect(v)
+ }
+}
+
+impl From<Disconnect> for Command {
+ fn from(v: Disconnect) -> Self {
+ Self::Disconnect(v)
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Attempt {
+ pub node: NodeId,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Connect {
+ pub node: NodeId,
+ pub now: LocalTime,
+ pub link: Link,
+ pub persistent: bool,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Disconnect {
+ pub node: NodeId,
+ pub since: LocalTime,
+ pub retry_at: Option<LocalTime>,
+}
diff --git a/crates/radicle-protocol/src/connections/effects.rs b/crates/radicle-protocol/src/connections/effects.rs
new file mode 100644
index 000000000..8711a97cf
--- /dev/null
+++ b/crates/radicle-protocol/src/connections/effects.rs
@@ -0,0 +1,100 @@
+//! External effects that are emitted by interacting with [`Connections`]. These
+//! effects should be used by the rest of the system to perform side-effects.
+//!
+//! [`Connections`]: super::Connections.
+
+use std::net::IpAddr;
+
+use localtime::LocalTime;
+use radicle::node::{Address, Link, NodeId, Severity};
+
+/// All effects that can occur from interacting with [`Connections`].
+///
+/// [`Connections`]: super::Connections.
+pub enum Effect {
+ Accept(Accept),
+ Connect(Connect),
+ Disconnect(Disconnect),
+}
+
+impl From<Accept> for Effect {
+ fn from(v: Accept) -> Self {
+ Self::Accept(v)
+ }
+}
+
+impl From<Connect> for Effect {
+ fn from(v: Connect) -> Self {
+ Self::Connect(v)
+ }
+}
+
+impl From<Disconnect> for Effect {
+ fn from(v: Disconnect) -> Self {
+ Self::Disconnect(v)
+ }
+}
+
+/// Effects that occur when checking for accepting a connection from an
+/// [`IpAddr`].
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Accept {
+ /// The [`IpAddr`] is likely a localhost connection.
+ LocalHost { ip: IpAddr },
+ /// The [`IpAddr`] should be accepted by the system, and later connected to.
+ Accepted { ip: IpAddr },
+}
+
+impl Accept {
+ /// The [`Accept::LocalHost`] should be created only if the [`IpAddr`] is
+ /// either a loopback address or has an 'unspecified' address (see
+ /// [`IpAddr::is_unspecified`]).
+ pub fn local_host(ip: IpAddr) -> Option<Self> {
+ (ip.is_loopback() || ip.is_unspecified()).then_some(Self::LocalHost { ip })
+ }
+
+ /// See [`Accept::Accepted`].
+ pub fn accepted(ip: IpAddr) -> Self {
+ Self::Accepted { ip }
+ }
+}
+
+/// Effects that occur when connecting a node.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Connect {
+ /// The set of initial messages should be sent to the [`NodeId`].
+ SendInitialMessages { node: NodeId, link: Link },
+ /// The [`IpAddr`] of the [`NodeId`] should be recorded in an external
+ /// database.
+ RecordIp {
+ node: NodeId,
+ ip: IpAddr,
+ clock: LocalTime,
+ },
+}
+
+/// Effects that occur when disconnecting a node.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Disconnect {
+ /// The connection to [`NodeId`] was disconnected, but re-connection should
+ /// be attempted at the given point in time.
+ RetryConnection {
+ /// The node that should be re-connected to.
+ node: NodeId,
+ /// When the node was disconnected.
+ since: LocalTime,
+ /// When the re-connection attempt should be made.
+ retry_at: LocalTime,
+ },
+ /// Record the severity of the disconnect reason.
+ RecordServerity {
+ /// The node that was disconnected.
+ node: NodeId,
+ /// The address of the node that was disconnected.
+ address: Address,
+ /// The severity of the disconnect reason.
+ severity: Severity,
+ },
+ /// Try to maintain all connections that are meant to be persistent.
+ MaintainConnections,
+}
diff --git a/crates/radicle-protocol/src/connections/events.rs b/crates/radicle-protocol/src/connections/events.rs
new file mode 100644
index 000000000..993ece8b0
--- /dev/null
+++ b/crates/radicle-protocol/src/connections/events.rs
@@ -0,0 +1,58 @@
+use std::net::IpAddr;
+
+use radicle::node::{Link, NodeId};
+
+use super::session;
+use super::session::Session;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Event {
+ Accept(Accept),
+ Connect(Box<Connect>),
+ Disconnect(Disconnect),
+}
+
+impl From<Disconnect> for Event {
+ fn from(v: Disconnect) -> Self {
+ Self::Disconnect(v)
+ }
+}
+
+impl From<Connect> for Event {
+ fn from(v: Connect) -> Self {
+ Self::Connect(Box::new(v))
+ }
+}
+
+impl From<Accept> for Event {
+ fn from(v: Accept) -> Self {
+ Self::Accept(v)
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Accept {
+ LimitExceeded { ip: IpAddr, current_inbound: usize },
+ IpBanned { ip: IpAddr },
+ HostLimited { ip: IpAddr },
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Connect {
+ AlreadyConnected {
+ session: Session<session::Connected>,
+ attempted_link: Link,
+ },
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Disconnect {
+ AlreadyDisconnected {
+ node: NodeId,
+ },
+ LinkConflict {
+ node: NodeId,
+ found: Link,
+ expected: Link,
+ },
+}
diff --git a/crates/radicle-protocol/src/connections/session.rs b/crates/radicle-protocol/src/connections/session.rs
new file mode 100644
index 000000000..b04449ef6
--- /dev/null
+++ b/crates/radicle-protocol/src/connections/session.rs
@@ -0,0 +1,562 @@
+use std::collections::{HashMap, HashSet, VecDeque};
+
+use localtime::{LocalDuration, LocalTime};
+use radicle::{
+ node::{Address, Link, NodeId, PingState},
+ prelude::RepoId,
+};
+
+use crate::service::message;
+
+/// Time after which a connection is considered stable.
+#[allow(unused)]
+pub const CONNECTION_STABLE_THRESHOLD: LocalDuration = LocalDuration::from_mins(1);
+
+#[derive(Clone, Debug)]
+pub enum State {
+ Initial(Initial),
+ Attempted(Attempted),
+ Connected(Connected),
+ Disconnected(Disconnected),
+}
+
+impl From<Initial> for State {
+ fn from(value: Initial) -> Self {
+ Self::Initial(value)
+ }
+}
+
+impl From<Attempted> for State {
+ fn from(value: Attempted) -> Self {
+ Self::Attempted(value)
+ }
+}
+
+impl From<Connected> for State {
+ fn from(value: Connected) -> Self {
+ Self::Connected(value)
+ }
+}
+
+impl From<Disconnected> for State {
+ fn from(value: Disconnected) -> Self {
+ Self::Disconnected(value)
+ }
+}
+
+impl HasAttempts for State {
+ fn attempts(&self) -> Attempts {
+ match self {
+ State::Initial(initial) => initial.attempts,
+ State::Attempted(attempted) => attempted.attempts,
+ State::Connected(connected) => connected.attempts,
+ State::Disconnected(disconnected) => disconnected.attempts,
+ }
+ }
+}
+
+pub struct Sessions {
+ initial: HashMap<NodeId, Session<Initial>>,
+ attempted: HashMap<NodeId, Session<Attempted>>,
+ disconnected: HashMap<NodeId, Session<Disconnected>>,
+ connected: HashMap<NodeId, Session<Connected>>,
+}
+
+impl Sessions {
+ /// Get the number of sessions that are connected and have an [inbound]
+ /// link.
+ ///
+ /// [inbound]: Link::Inbound
+ pub fn connected_inbound(&self) -> usize {
+ self.connected
+ .values()
+ .filter(|session| session.link().is_inbound())
+ .count()
+ }
+
+ /// Get the number of sessions that are connected and have an [outbound]
+ /// link.
+ ///
+ /// [outbound]: Link::Outbound
+ pub fn connected_outbound(&self) -> usize {
+ self.connected
+ .values()
+ .filter(|session| session.link().is_outbound())
+ .count()
+ }
+
+ /// Checks that an existing [`Session`] exists for the given [`NodeId`].
+ pub fn has_session_for(&self, node: &NodeId) -> bool {
+ self.initial.contains_key(node)
+ || self.attempted.contains_key(node)
+ || self.disconnected.contains_key(node)
+ || self.connected.contains_key(node)
+ }
+
+ /// Get all [`Session`]s that are in the [`Connected`] state, along with
+ /// their [`NodeId`]s.
+ pub fn connected(&self) -> impl Iterator<Item = (&NodeId, &Session<Connected>)> {
+ self.connected.iter()
+ }
+
+ /// Transition the [`Session`], identified by the [`NodeId`], to the
+ /// [`Attempted`] state.
+ ///
+ /// If the [`Session`] does not exist, then `None` is returned.
+ pub fn session_to_attempted(&mut self, node: &NodeId) -> Option<Session<Attempted>> {
+ let s = self.initial.remove(node)?.into_attempted();
+ self.attempted.insert(*node, s.clone());
+ Some(s)
+ }
+
+ /// Transition the [`Session`], identified by the [`NodeId`], to the
+ /// [`Disconnected`] state.
+ ///
+ /// The time this [`Session`] was disconnected is marked by `since`, and if
+ /// the connection should be retried then a `retry_at` value should be
+ /// provided.
+ ///
+ /// If the [`Session`] does not exist, then `None` is returned.
+ pub fn session_to_disconnected(
+ &mut self,
+ node: &NodeId,
+ since: LocalTime,
+ retry_at: Option<LocalTime>,
+ ) -> Option<Session<Disconnected>> {
+ match self.remove_session(node) {
+ None => None,
+ Some(session) => {
+ let s = session.into_disconnected(since, retry_at);
+ self.disconnected.insert(*node, s.clone());
+ Some(s)
+ }
+ }
+ }
+
+ /// Transition the [`Session`], identified by the [`NodeId`], to the
+ /// [`Connected`] state.
+ ///
+ /// The [`Session`] is last active given by the time given for `now`, the
+ /// type of [`Link`] is also marked by the provided value, and also keep
+ /// track of whether the session should be persisted.
+ ///
+ /// If the [`Session`] does not exist, then `None` is returned.
+ pub fn session_to_connected(
+ &mut self,
+ node: &NodeId,
+ now: LocalTime,
+ link: Link,
+ persistent: bool,
+ ) -> Option<Session<Connected>> {
+ let s = self.remove_session(node)?;
+ let state = match s.state {
+ State::Initial(initial) => Connected::from_initial(initial, now),
+ State::Attempted(attempted) => Connected::from_attempted(attempted, now),
+ State::Connected(connected) => connected,
+ State::Disconnected(disconnected) => Connected::from_disconnected(disconnected, now),
+ };
+ Some(Session {
+ state,
+ id: s.id,
+ addr: s.addr,
+ link,
+ persistent,
+ last_active: now,
+ subscribe: s.subscribe,
+ })
+ }
+
+ /// Transition a [`Disconnected`] [`Session`] into an [`Initial`] state,
+ /// meaning that it should be re-connected to.
+ ///
+ /// If the [`NodeId`] was not in a [`Disconnected`] state then `None` is
+ /// returned.
+ pub fn reconnect(&mut self, node: &NodeId) -> Option<Session<Initial>> {
+ let s = self.disconnected.remove(node)?.into_initial();
+ self.initial.insert(*node, s.clone());
+ Some(s)
+ }
+
+ /// Get a [`Session`] that can be in any [`State`].
+ pub fn get_session(&self, node: &NodeId) -> Option<Session<State>> {
+ self.initial
+ .get(node)
+ .cloned()
+ .map(|s| s.into_any_state())
+ .or_else(|| {
+ self.attempted
+ .get(node)
+ .cloned()
+ .map(|s| s.into_any_state())
+ })
+ .or_else(|| {
+ self.disconnected
+ .get(node)
+ .cloned()
+ .map(|s| s.into_any_state())
+ })
+ .or_else(|| {
+ self.connected
+ .get(node)
+ .cloned()
+ .map(|s| s.into_any_state())
+ })
+ }
+
+ fn remove_session(&mut self, node: &NodeId) -> Option<Session<State>> {
+ self.initial
+ .remove(node)
+ .map(|s| s.into_any_state())
+ .or_else(|| self.attempted.remove(node).map(|s| s.into_any_state()))
+ .or_else(|| self.disconnected.remove(node).map(|s| s.into_any_state()))
+ .or_else(|| self.connected.remove(node).map(|s| s.into_any_state()))
+ }
+
+ /// Get the [`Session`], for the given [`NodeId`], that is expected to be in
+ /// the [`Connected`] state.
+ pub fn get_connected(&self, node: &NodeId) -> Option<&Session<Connected>> {
+ self.connected.get(node)
+ }
+
+ #[allow(unused)]
+ fn inbound(&mut self, node: NodeId, addr: Address, persistent: bool, now: LocalTime) {
+ self.connected
+ .insert(node, Session::inbound(node, addr, persistent, now));
+ }
+}
+
+pub trait HasAttempts {
+ fn attempts(&self) -> Attempts;
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct Attempts {
+ /// Connection attempts. For persistent peers, Tracks
+ /// how many times we've attempted to connect. We reset this to zero
+ /// upon successful connection, once the connection is stable.
+ attempts: usize,
+}
+
+impl Attempts {
+ fn new(attempts: usize) -> Self {
+ Attempts { attempts }
+ }
+
+ pub fn attempted(self) -> Self {
+ Self {
+ attempts: self.attempts + 1,
+ }
+ }
+
+ pub fn reset(&mut self) {
+ self.attempts = 0;
+ }
+
+ pub fn attempts(&self) -> usize {
+ self.attempts
+ }
+
+ pub(super) fn as_u32(&self) -> u32 {
+ self.attempts as u32
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Session<S> {
+ /// The [`NodeId`] of the session.
+ id: NodeId,
+ /// The public protocol [`Address`] for the session.
+ addr: Address,
+ /// The [`Link`] direction for the session.
+ link: Link,
+ /// Keep track of whether the session should be persisted. That is, if it is
+ /// disconnected, re-connection attempts should be made.
+ persistent: bool,
+ /// Last time a message was received from the peer.
+ last_active: LocalTime,
+ /// Peer subscription.
+ subscribe: Option<message::Subscribe>,
+ /// The state the session is in. Can be in the following states:
+ /// - [`Initial`]
+ /// - [`Attempted`]
+ /// - [`Disconnected`]
+ /// - [`Connected`]
+ state: S,
+}
+
+impl<S: HasAttempts> HasAttempts for Session<S> {
+ fn attempts(&self) -> Attempts {
+ self.state.attempts()
+ }
+}
+
+impl<S> Session<S> {
+ pub fn node(&self) -> NodeId {
+ self.id
+ }
+
+ pub fn address(&self) -> &Address {
+ &self.addr
+ }
+
+ /// Set the [`message::Subscribe`] of this [`Session`].
+ pub fn set_subscription(&mut self, subscription: message::Subscribe) {
+ self.subscribe = Some(subscription);
+ }
+
+ /// Subscribe to the given [`RepoId`], if the [`message::Subscribe`] has
+ /// been set.
+ pub fn subscribe_to(&mut self, rid: &RepoId) {
+ if let Some(ref mut sub) = self.subscribe {
+ sub.filter.insert(rid);
+ }
+ }
+
+ pub fn last_active(&self) -> &LocalTime {
+ &self.last_active
+ }
+
+ pub fn link(&self) -> &Link {
+ &self.link
+ }
+
+ pub fn as_outbound(&mut self) {
+ self.link = Link::Outbound;
+ }
+
+ pub fn into_disconnected(
+ self,
+ since: LocalTime,
+ retry_at: Option<LocalTime>,
+ ) -> Session<Disconnected>
+ where
+ S: HasAttempts,
+ {
+ self.map(|s| Disconnected {
+ since,
+ retry_at,
+ attempts: s.attempts(),
+ })
+ }
+
+ #[allow(unused)]
+ fn seen(&mut self, since: LocalTime) {
+ self.last_active = since;
+ }
+
+ fn into_any_state<T>(self) -> Session<T>
+ where
+ T: From<S>,
+ {
+ self.map(|state| state.into())
+ }
+
+ fn map<T, F>(self, f: F) -> Session<T>
+ where
+ F: FnOnce(S) -> T,
+ {
+ Session {
+ id: self.id,
+ addr: self.addr,
+ link: self.link,
+ persistent: self.persistent,
+ last_active: self.last_active,
+ subscribe: self.subscribe,
+ state: f(self.state),
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct Initial {
+ attempts: Attempts,
+}
+
+impl Initial {
+ pub fn new() -> Self {
+ Self::with_attempts(Attempts::new(1))
+ }
+
+ pub fn with_attempts(attempts: Attempts) -> Self {
+ Self { attempts }
+ }
+}
+
+impl Default for Initial {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Session<Initial> {
+ pub fn outbound(id: NodeId, addr: Address, persistent: bool, last_active: LocalTime) -> Self {
+ Self {
+ id,
+ addr,
+ link: Link::Outbound,
+ persistent,
+ state: Initial::new(),
+ last_active,
+ subscribe: None,
+ }
+ }
+
+ /// Transition the [`Session`] to an [`Attempted`] state, incrementing the
+ /// number of attempts made.
+ pub fn into_attempted(self) -> Session<Attempted> {
+ self.map(|s| Attempted::new(s.attempts.attempted()))
+ }
+
+ /// Transition the [`Session`] into the [`Connected`] state.
+ pub fn into_connected(self, since: LocalTime) -> Session<Connected> {
+ self.map(|s| Connected::new(since, s.attempts))
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Attempted {
+ attempts: Attempts,
+}
+
+impl Attempted {
+ pub fn new(attempts: Attempts) -> Self {
+ Attempted { attempts }
+ }
+}
+
+impl Session<Attempted> {
+ /// Transition the [`Session`] into the [`Connected`] state.
+ pub fn into_connected(self, since: LocalTime) -> Session<Connected> {
+ self.map(|s| Connected::new(since, s.attempts))
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Connected {
+ /// Connected since this time.
+ since: LocalTime,
+ /// Ping state.
+ ping: PingState,
+ /// Ongoing fetches.
+ fetching: HashSet<RepoId>,
+ /// Measured latencies for this peer.
+ latencies: VecDeque<LocalDuration>,
+ /// Whether the connection is stable.
+ stable: bool,
+ /// Number of attempts over the lifetime of the connection. This includes if
+ /// the connection is degraded back to an [`Initial`] state through a
+ /// [`Session::reconnect`].
+ attempts: Attempts,
+}
+
+impl HasAttempts for Connected {
+ fn attempts(&self) -> Attempts {
+ self.attempts
+ }
+}
+
+impl Connected {
+ /// Create a new [`Connected`] state, where `since` is the time of
+ /// connection, and `attempts` is the number of attempted connections in the
+ /// lifetime of the [`Session`].
+ pub fn new(since: LocalTime, attempts: Attempts) -> Self {
+ Self {
+ since,
+ ping: PingState::default(),
+ fetching: HashSet::default(),
+ latencies: VecDeque::default(),
+ stable: false,
+ attempts,
+ }
+ }
+
+ /// Create a fresh [`Connected`] state, using `since` as the [`LocalTime`] for
+ /// when this connection was made.
+ pub fn fresh(since: LocalTime) -> Self {
+ Self::new(since, Attempts::new(0))
+ }
+
+ fn from_initial(initial: Initial, since: LocalTime) -> Self {
+ Self::new(since, initial.attempts)
+ }
+
+ fn from_attempted(attempted: Attempted, since: LocalTime) -> Self {
+ Self::new(since, attempted.attempts)
+ }
+
+ fn from_disconnected(disconnected: Disconnected, since: LocalTime) -> Self {
+ Self::new(since, disconnected.attempts)
+ }
+}
+
+pub struct Ping {
+ since: LocalTime,
+ rng: fastrand::Rng,
+}
+
+impl Session<Connected> {
+ pub fn inbound(id: NodeId, addr: Address, persistent: bool, now: LocalTime) -> Self {
+ Self {
+ id,
+ addr,
+ link: Link::Inbound,
+ persistent,
+ last_active: now,
+ subscribe: None,
+ state: Connected::fresh(now),
+ }
+ }
+
+ /// Checks if the [`Session`] is inactive, i.e. the time passed is greater
+ /// than the `delta`.
+ pub fn is_inactive(&self, now: &LocalTime, delta: LocalDuration) -> bool {
+ *now - self.last_active >= delta
+ }
+
+ pub fn ping(&mut self, mut ping: Ping) -> message::Ping {
+ let msg = message::Ping::new(&mut ping.rng);
+ self.state.ping = PingState::AwaitingResponse {
+ len: msg.ponglen,
+ since: ping.since,
+ };
+ msg
+ }
+
+ pub fn idle(&mut self, now: LocalTime, stable_threshold: LocalDuration) {
+ let Connected {
+ since,
+ ref mut stable,
+ ref mut attempts,
+ ..
+ } = self.state;
+ if now >= since && now.duration_since(since) >= stable_threshold {
+ *stable = true;
+ attempts.reset();
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Disconnected {
+ /// Since when has this peer been disconnected.
+ since: LocalTime,
+ /// When to retry the connection.
+ retry_at: Option<LocalTime>,
+ /// Number of attempts while disconnected.
+ attempts: Attempts,
+}
+
+impl Session<Disconnected> {
+ pub fn disconnected_since(&self) -> &LocalTime {
+ &self.state.since
+ }
+
+ pub fn should_retry_at(&self) -> Option<&LocalTime> {
+ self.state.retry_at.as_ref()
+ }
+
+ /// Transition the [`Session`] to an [`Initial`] state.
+ fn into_initial(self) -> Session<Initial> {
+ self.map(|s| Initial::with_attempts(s.attempts))
+ }
+}
diff --git a/crates/radicle-protocol/src/lib.rs b/crates/radicle-protocol/src/lib.rs
index 910e4af23..a54b764c1 100644
--- a/crates/radicle-protocol/src/lib.rs
+++ b/crates/radicle-protocol/src/lib.rs
@@ -4,6 +4,7 @@ pub mod service;
pub mod wire;
pub mod worker;
+pub mod connections;
pub mod tasks;
/// Peer-to-peer protocol version.
commit 1a43ebeff41cea3750472e69bc953b27c257c408
Author: Fintan Halpenny <fintan.halpenny@gmail.com>
Date: Thu Jul 24 16:12:55 2025 +0100
protocol: port Service::wake to sans-IO
This change ports the `Service::wake` method (provided below for context) to a
sans-IO, state machine approach.
The machine is represented by the `TaskTimers` and uses an event source style,
where the `tick` method provides the set of task events that should be acted
upon, alongside the timer events for advancing the `TaskTimers` state machine.
```rust
pub fn wake(&mut self) {
let now = self.clock;
trace!(
target: "service",
"Wake +{}",
now - self.started_at.expect("Service::wake: service must be initialized")
);
if now - self.last_idle >= IDLE_INTERVAL {
trace!(target: "service", "Running 'idle' task...");
self.keep_alive(&now);
self.disconnect_unresponsive_peers(&now);
self.idle_connections();
self.maintain_connections();
self.dequeue_fetches();
self.outbox.wakeup(IDLE_INTERVAL);
self.last_idle = now;
}
if now - self.last_gossip >= GOSSIP_INTERVAL {
trace!(target: "service", "Running 'gossip' task...");
if let Err(e) = self.relay_announcements() {
error!(target: "service", "Error relaying stored announcements: {e}");
}
self.outbox.wakeup(GOSSIP_INTERVAL);
self.last_gossip = now;
}
if now - self.last_sync >= SYNC_INTERVAL {
trace!(target: "service", "Running 'sync' task...");
if let Err(e) = self.fetch_missing_repositories() {
error!(target: "service", "Error fetching missing inventory: {e}");
}
self.outbox.wakeup(SYNC_INTERVAL);
self.last_sync = now;
}
if now - self.last_announce >= ANNOUNCE_INTERVAL {
trace!(target: "service", "Running 'announce' task...");
self.announce_inventory();
self.outbox.wakeup(ANNOUNCE_INTERVAL);
self.last_announce = now;
}
if now - self.last_prune >= PRUNE_INTERVAL {
trace!(target: "service", "Running 'prune' task...");
if let Err(err) = self.prune_routing_entries(&now) {
error!(target: "service", "Error pruning routing entries: {err}");
}
if let Err(err) = self
.db
.gossip_mut()
.prune((now - self.config.limits.gossip_max_age).into())
{
error!(target: "service", "Error pruning gossip entries: {err}");
}
self.outbox.wakeup(PRUNE_INTERVAL);
self.last_prune = now;
}
// Always check whether there are persistent peers that need reconnecting.
self.maintain_persistent();
}
```
diff --git a/crates/radicle-protocol/src/lib.rs b/crates/radicle-protocol/src/lib.rs
index 9c20f918e..910e4af23 100644
--- a/crates/radicle-protocol/src/lib.rs
+++ b/crates/radicle-protocol/src/lib.rs
@@ -4,5 +4,7 @@ pub mod service;
pub mod wire;
pub mod worker;
+pub mod tasks;
+
/// Peer-to-peer protocol version.
pub const PROTOCOL_VERSION: u8 = 1;
diff --git a/crates/radicle-protocol/src/tasks.rs b/crates/radicle-protocol/src/tasks.rs
new file mode 100644
index 000000000..50ab00fef
--- /dev/null
+++ b/crates/radicle-protocol/src/tasks.rs
@@ -0,0 +1,838 @@
+use localtime::{LocalDuration, LocalTime};
+use nonempty::{nonempty, NonEmpty};
+
+/// How often to run the "idle" task.
+pub const IDLE_INTERVAL: LocalDuration = LocalDuration::from_secs(30);
+/// How often to run the "gossip" task.
+pub const GOSSIP_INTERVAL: LocalDuration = LocalDuration::from_secs(6);
+/// How often to run the "announce" task.
+pub const ANNOUNCE_INTERVAL: LocalDuration = LocalDuration::from_mins(60);
+/// How often to run the "sync" task.
+pub const SYNC_INTERVAL: LocalDuration = LocalDuration::from_secs(60);
+/// How often to run the "prune" task.
+pub const PRUNE_INTERVAL: LocalDuration = LocalDuration::from_mins(30);
+
+/// The [`TaskTimers`] keeps track of the state of different timers and duration
+/// intervals for when to emit a set of tasks.
+///
+/// [`TaskTimers::tick`] checks which intervals have elapsed and produces a
+/// [`TaskTimerCommand`].
+///
+/// The [`TaskTimerCommand`] will provide a set of [`TimerEvent`]s which can be
+/// used to [`TaskTimers::advance`] the clocks forward.
+///
+/// It also provides a set [`TaskEvent`]s which are tasks that the rest of the
+/// system should execute.
+pub struct TaskTimers {
+ last_idle: LocalTime,
+ last_gossip: LocalTime,
+ last_sync: LocalTime,
+ last_announce: LocalTime,
+ last_prune: LocalTime,
+ intervals: Intervals,
+}
+
+/// Interval durations used in [`TaskTimers`] for deciding when to issue
+/// [`TaskEvent`]s and [`TimerEvent`]s.
+///
+/// The default values for each interval are given by:
+/// - Idle: 30s
+/// - Gossip: 6s
+/// - Sync: 60s
+/// - Announce: 60m
+/// - Prune: 30m
+pub struct Intervals {
+ pub idle: LocalDuration,
+ pub gossip: LocalDuration,
+ pub sync: LocalDuration,
+ pub announce: LocalDuration,
+ pub prune: LocalDuration,
+}
+
+impl Default for Intervals {
+ fn default() -> Self {
+ Self {
+ idle: IDLE_INTERVAL,
+ gossip: GOSSIP_INTERVAL,
+ sync: SYNC_INTERVAL,
+ announce: ANNOUNCE_INTERVAL,
+ prune: PRUNE_INTERVAL,
+ }
+ }
+}
+
+impl Intervals {
+ /// The set of [`Intervals`] that never elapse.
+ pub const NEVER: Intervals = Intervals {
+ idle: LocalDuration::MAX,
+ gossip: LocalDuration::MAX,
+ sync: LocalDuration::MAX,
+ announce: LocalDuration::MAX,
+ prune: LocalDuration::MAX,
+ };
+
+ /// The set of [`Intervals`] that always elapse – as long as at least a
+ /// millisecond of time passes.
+ pub const ALWAYS: Intervals = Intervals {
+ idle: LocalDuration::from_millis(0),
+ gossip: LocalDuration::from_millis(0),
+ sync: LocalDuration::from_millis(0),
+ announce: LocalDuration::from_millis(0),
+ prune: LocalDuration::from_millis(0),
+ };
+
+ /// Set the idle interval – issues tasks based on the node's idleness.
+ pub fn with_idle(mut self, idle: LocalDuration) -> Self {
+ self.idle = idle;
+ self
+ }
+
+ /// Set the gossip interval – issues tasks for gossiping to the network.
+ pub fn with_gossip(mut self, gossip: LocalDuration) -> Self {
+ self.gossip = gossip;
+ self
+ }
+
+ /// Set the sync interval – issues tasks for syncing with the network.
+ pub fn with_sync(mut self, sync: LocalDuration) -> Self {
+ self.sync = sync;
+ self
+ }
+
+ /// Set the announce interval – issues tasks for announcing changes to the
+ /// network.
+ pub fn with_announce(mut self, announce: LocalDuration) -> Self {
+ self.announce = announce;
+ self
+ }
+
+ /// Set the prune interval – issues tasks for cleaning up stale data on the
+ /// node.
+ pub fn with_prune(mut self, prune: LocalDuration) -> Self {
+ self.prune = prune;
+ self
+ }
+}
+
+/// Task events that are emitted by the [`TaskTimers`].
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum TaskEvent {
+ /// Maintain any configured persistent connections.
+ MaintainPersistentConnections,
+ /// Idle tasks.
+ Idle(Idle),
+ /// Gossip tasks.
+ Gossip(Gossip),
+ /// Synchronization tasks.
+ Sync(Sync),
+ /// Announcement tasks.
+ Announce(Announce),
+ /// Prune tasks.
+ Prune(Prune),
+}
+
+impl TaskEvent {
+ /// Produce all [`TaskEvent`]s.
+ pub fn all() -> NonEmpty<Self> {
+ let mut events = nonempty![TaskEvent::MaintainPersistentConnections];
+ events.extend(Idle::all().map(Self::from));
+ events.extend(Gossip::all().map(Self::from));
+ events.extend(Sync::all().map(Self::from));
+ events.extend(Announce::all().map(Self::from));
+ events.extend(Prune::all().map(Self::from));
+ events
+ }
+}
+
+/// Events that describe how timer state should change.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
+pub enum TimerEvent {
+ /// Advance the idle clock of [`TaskTimers`].
+ AdvanceIdle(LocalTime),
+ /// Advance the gossip clock of [`TaskTimers`].
+ AdvanceGossip(LocalTime),
+ /// Advance the sync clock of [`TaskTimers`].
+ AdvanceSync(LocalTime),
+ /// Advance the announce clock of [`TaskTimers`].
+ AdvanceAnnounce(LocalTime),
+ /// Advance the prune clock of [`TaskTimers`].
+ AdvancePrune(LocalTime),
+}
+
+/// Tasks for the machine to perform while it is idling.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Idle {
+ /// Maintain any existing connections.
+ MaintainConnections,
+ /// Issue a keep alive message to connections.
+ KeepAlive,
+ /// Disconnect any unresponsive peers.
+ DisconnectUnresponsivePeers,
+ /// Dequeue any queued fetches.
+ DequeueFetches,
+}
+
+impl Idle {
+ /// Return all the [`Idle`] variants.
+ pub fn all() -> NonEmpty<Self> {
+ nonempty![
+ Self::MaintainConnections,
+ Self::KeepAlive,
+ Self::DisconnectUnresponsivePeers,
+ Self::DequeueFetches,
+ ]
+ }
+}
+
+impl From<Idle> for TaskEvent {
+ fn from(value: Idle) -> Self {
+ TaskEvent::Idle(value)
+ }
+}
+
+/// Gossip tasks for the machine to execute.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Gossip {
+ /// Relay announcements to connections.
+ RelayAnnouncements,
+}
+
+impl Gossip {
+ /// Return all the [`Gossip`] variants.
+ pub fn all() -> NonEmpty<Self> {
+ nonempty![Self::RelayAnnouncements]
+ }
+}
+
+impl From<Gossip> for TaskEvent {
+ fn from(value: Gossip) -> Self {
+ TaskEvent::Gossip(value)
+ }
+}
+
+/// Synchronization tasks for the machine to execute.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Sync {
+ /// Fetch missing repositories from connections. Missing repositories are
+ /// repositories that are seeded, but not in storage.
+ MissingRepositories,
+}
+
+impl Sync {
+ /// Return all the [`Sync`] variants.
+ pub fn all() -> NonEmpty<Self> {
+ nonempty![Self::MissingRepositories]
+ }
+}
+
+impl From<Sync> for TaskEvent {
+ fn from(value: Sync) -> Self {
+ TaskEvent::Sync(value)
+ }
+}
+
+/// Announcement tasks for the machine to execute.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Announce {
+ /// Announce inventory to connections.
+ Inventory,
+}
+
+impl Announce {
+ /// Return all the [`Announce`] variants.
+ pub fn all() -> NonEmpty<Self> {
+ nonempty![Self::Inventory]
+ }
+}
+
+impl From<Announce> for TaskEvent {
+ fn from(value: Announce) -> Self {
+ TaskEvent::Announce(value)
+ }
+}
+
+/// Pruning tasks for the machine to execute.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Prune {
+ /// Prune any routing entries that are no longer required.
+ RoutingEntries,
+ /// Prune any announcements that are no longer required.
+ Announcements,
+}
+
+impl Prune {
+ /// Return all the [`Prune`] variants.
+ pub fn all() -> NonEmpty<Self> {
+ nonempty![Self::RoutingEntries, Self::Announcements]
+ }
+}
+
+impl From<Prune> for TaskEvent {
+ fn from(value: Prune) -> Self {
+ TaskEvent::Prune(value)
+ }
+}
+
+/// The result of performing a [`TaskTimers::tick`].
+pub struct TaskTimerCommand {
+ /// The set of tasks that should be performed next.
+ pub tasks: NonEmpty<TaskEvent>,
+ /// The set of timers that should be used to advance the [`TaskTimers`]
+ /// ([`TaskTimers::advance`]).
+ pub timers: Vec<TimerEvent>,
+}
+
+impl TaskTimers {
+ /// Construct the [`Timers`] starting all timers at `now`.
+ pub fn new(now: LocalTime) -> Self {
+ Self {
+ last_idle: now,
+ last_gossip: now,
+ last_sync: now,
+ last_announce: now,
+ last_prune: now,
+ intervals: Intervals::default(),
+ }
+ }
+
+ /// Set the [`Intervals`] for the [`Timers`].
+ pub fn with_intervals(mut self, intervals: Intervals) -> Self {
+ self.intervals = intervals;
+ self
+ }
+
+ /// Issue [`TaskEvent`]s and [`TimerEvent`]s based on the [`Intervals`] of
+ /// the timers, and the time passed in `now`.
+ ///
+ /// The [`TimerEvent`]s can be used to advance the timers, using
+ /// [`Timers::advance`].
+ pub fn tick(&self, now: LocalTime) -> TaskTimerCommand {
+ let mut tasks = NonEmpty::new(TaskEvent::MaintainPersistentConnections);
+ let mut timers = Vec::with_capacity(5);
+
+ if self.has_idle_elapsed(now) {
+ tasks.extend(Idle::all().map(TaskEvent::from));
+ timers.push(TimerEvent::AdvanceIdle(now));
+ }
+
+ if self.has_gossip_elapsed(now) {
+ tasks.extend(Gossip::all().map(TaskEvent::from));
+ timers.push(TimerEvent::AdvanceGossip(now));
+ }
+
+ if self.has_sync_elapsed(now) {
+ tasks.extend(Sync::all().map(TaskEvent::from));
+ timers.push(TimerEvent::AdvanceSync(now));
+ }
+
+ if self.has_announce_elapsed(now) {
+ tasks.extend(Announce::all().map(TaskEvent::from));
+ timers.push(TimerEvent::AdvanceAnnounce(now));
+ }
+
+ if self.has_prune_elapsed(now) {
+ tasks.extend(Prune::all().map(TaskEvent::from));
+ timers.push(TimerEvent::AdvancePrune(now));
+ }
+
+ TaskTimerCommand { tasks, timers }
+ }
+
+ /// Apply [`TimerEvent`]s to advance their clocks.
+ pub fn advance(&mut self, events: &[TimerEvent]) {
+ for event in events {
+ self.advance_timer(event);
+ }
+ }
+
+ fn advance_timer(&mut self, event: &TimerEvent) {
+ match event {
+ TimerEvent::AdvanceIdle(time) => self.last_idle = *time,
+ TimerEvent::AdvanceGossip(time) => self.last_gossip = *time,
+ TimerEvent::AdvanceSync(time) => self.last_sync = *time,
+ TimerEvent::AdvanceAnnounce(time) => self.last_announce = *time,
+ TimerEvent::AdvancePrune(time) => self.last_prune = *time,
+ }
+ }
+
+ fn has_idle_elapsed(&self, now: LocalTime) -> bool {
+ now - self.last_idle >= self.intervals.idle
+ }
+
+ fn has_gossip_elapsed(&self, now: LocalTime) -> bool {
+ now - self.last_gossip >= self.intervals.gossip
+ }
+
+ fn has_sync_elapsed(&self, now: LocalTime) -> bool {
+ now - self.last_sync >= self.intervals.sync
+ }
+
+ fn has_announce_elapsed(&self, now: LocalTime) -> bool {
+ now - self.last_announce >= self.intervals.announce
+ }
+
+ fn has_prune_elapsed(&self, now: LocalTime) -> bool {
+ now - self.last_prune >= self.intervals.prune
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use localtime::{LocalDuration, LocalTime};
+ use nonempty::nonempty;
+
+ // Helper function to create a test time
+ fn test_time(secs: u64) -> LocalTime {
+ LocalTime::from_secs(secs)
+ }
+
+ // Helper function to create test duration
+ fn test_duration(secs: u64) -> LocalDuration {
+ LocalDuration::from_secs(secs)
+ }
+
+ fn assert_tasks(got: &NonEmpty<TaskEvent>, expected: NonEmpty<TaskEvent>) {
+ assert_eq!(
+ got.len(),
+ expected.len(),
+ "extra task(s) emitted: {:?}",
+ got
+ );
+ for t in expected {
+ assert!(got.contains(&t), "missing expected task: {t:?}")
+ }
+ }
+
+ fn assert_timers(got: &Vec<TimerEvent>, expected: Vec<TimerEvent>) {
+ assert_eq!(
+ got.len(),
+ expected.len(),
+ "extra timer(s) emitted: {:?}",
+ got
+ );
+ for t in expected {
+ assert!(got.contains(&t), "missing expected timer: {t:?}")
+ }
+ }
+
+ fn gen_duration(seed: usize) -> LocalDuration {
+ LocalDuration::from_secs(radicle::test::arbitrary::gen(seed))
+ }
+
+ #[test]
+ fn test_tick_at_start_time_only_persistent_connections() {
+ let start_time = test_time(1000);
+ let timers = TaskTimers::new(start_time).with_intervals(Intervals::NEVER);
+
+ let command = timers.tick(start_time);
+
+ assert_eq!(
+ command.tasks,
+ nonempty![TaskEvent::MaintainPersistentConnections]
+ );
+ assert_eq!(command.timers, vec![]);
+ }
+
+ #[test]
+ fn test_tick_idle_interval_elapsed() {
+ let start_time = test_time(1000);
+ let timers = TaskTimers::new(start_time).with_intervals(Intervals {
+ idle: LocalDuration::from_secs(1),
+ ..Intervals::NEVER
+ });
+
+ // Advance time by exactly the idle interval
+ let tick_time = start_time + test_duration(2);
+ let command = timers.tick(tick_time);
+
+ let mut expected = nonempty![TaskEvent::MaintainPersistentConnections];
+ expected.append(&mut Idle::all().map(TaskEvent::from).into());
+ assert_tasks(&command.tasks, expected);
+ assert_timers(&command.timers, vec![TimerEvent::AdvanceIdle(tick_time)]);
+ }
+
+ #[test]
+ fn test_tick_gossip_only() {
+ let start_time = test_time(1000);
+ let timers = TaskTimers::new(start_time).with_intervals(Intervals {
+ gossip: LocalDuration::from_secs(1),
+ ..Intervals::NEVER
+ });
+
+ let tick_time = start_time + test_duration(2);
+ let command = timers.tick(tick_time);
+
+ let mut expected = nonempty![TaskEvent::MaintainPersistentConnections];
+ expected.append(&mut Gossip::all().map(TaskEvent::from).into());
+ assert_tasks(&command.tasks, expected);
+ assert_timers(&command.timers, vec![TimerEvent::AdvanceGossip(tick_time)]);
+ }
+
+ #[test]
+ fn test_tick_sync_interval_elapsed() {
+ let start_time = test_time(1000);
+ let timers = TaskTimers::new(start_time).with_intervals(Intervals {
+ sync: LocalDuration::from_secs(1),
+ ..Intervals::NEVER
+ });
+
+ let tick_time = start_time + test_duration(2);
+ let command = timers.tick(tick_time);
+
+ let mut expected = nonempty![TaskEvent::MaintainPersistentConnections];
+ expected.append(&mut Sync::all().map(TaskEvent::from).into());
+ assert_tasks(&command.tasks, expected);
+ assert_timers(&command.timers, vec![TimerEvent::AdvanceSync(tick_time)]);
+ }
+
+ #[test]
+ fn test_tick_announce_interval_elapsed() {
+ let start_time = test_time(1000);
+ let timers = TaskTimers::new(start_time).with_intervals(Intervals {
+ announce: LocalDuration::from_secs(1),
+ ..Intervals::NEVER
+ });
+
+ let tick_time = start_time + test_duration(2);
+ let command = timers.tick(tick_time);
+
+ let mut expected = nonempty![TaskEvent::MaintainPersistentConnections];
+ expected.append(&mut Announce::all().map(TaskEvent::from).into());
+ assert_tasks(&command.tasks, expected);
+ assert_timers(
+ &command.timers,
+ vec![TimerEvent::AdvanceAnnounce(tick_time)],
+ );
+ }
+
+ #[test]
+ fn test_tick_prune_interval_elapsed() {
+ let start_time = test_time(1000);
+ let timers = TaskTimers::new(start_time).with_intervals(Intervals {
+ prune: LocalDuration::from_secs(1),
+ ..Intervals::NEVER
+ });
+
+ let tick_time = start_time + test_duration(2);
+ let command = timers.tick(tick_time);
+
+ let mut expected = nonempty![TaskEvent::MaintainPersistentConnections];
+ expected.append(&mut Prune::all().map(TaskEvent::from).into());
+ assert_tasks(&command.tasks, expected);
+ assert_timers(&command.timers, vec![TimerEvent::AdvancePrune(tick_time)]);
+ }
+
+ #[test]
+ fn test_tick_multiple_intervals_elapsed() {
+ let start_time = test_time(1000);
+ let timers = TaskTimers::new(start_time).with_intervals(Intervals {
+ idle: LocalDuration::from_secs(1),
+ gossip: LocalDuration::from_secs(1),
+ sync: LocalDuration::from_secs(1),
+ ..Intervals::NEVER
+ });
+
+ let tick_time = start_time + test_duration(2);
+ let command = timers.tick(tick_time);
+
+ let mut expected = nonempty![TaskEvent::MaintainPersistentConnections];
+ expected.append(&mut Idle::all().map(TaskEvent::from).into());
+ expected.append(&mut Gossip::all().map(TaskEvent::from).into());
+ expected.append(&mut Sync::all().map(TaskEvent::from).into());
+ assert_tasks(&command.tasks, expected);
+ assert_timers(
+ &command.timers,
+ vec![
+ TimerEvent::AdvanceIdle(tick_time),
+ TimerEvent::AdvanceGossip(tick_time),
+ TimerEvent::AdvanceSync(tick_time),
+ ],
+ );
+ }
+
+ #[test]
+ fn test_tick_all_intervals_elapsed() {
+ let start_time = test_time(1000);
+ let timers = TaskTimers::new(start_time).with_intervals(Intervals::ALWAYS);
+
+ let tick_time = start_time + test_duration(1);
+ let command = timers.tick(tick_time);
+
+ assert_tasks(&command.tasks, TaskEvent::all());
+ assert_timers(
+ &command.timers,
+ vec![
+ TimerEvent::AdvanceIdle(tick_time),
+ TimerEvent::AdvanceGossip(tick_time),
+ TimerEvent::AdvanceSync(tick_time),
+ TimerEvent::AdvanceAnnounce(tick_time),
+ TimerEvent::AdvancePrune(tick_time),
+ ],
+ );
+ }
+
+ #[test]
+ fn test_advance_single_timer() {
+ let start_time = test_time(1000);
+ let mut timers = TaskTimers::new(start_time);
+
+ let new_time = test_time(2000);
+ let events = vec![TimerEvent::AdvanceIdle(new_time)];
+
+ timers.advance(&events);
+
+ assert_eq!(timers.last_idle, new_time);
+ assert_eq!(timers.last_gossip, start_time);
+ assert_eq!(timers.last_sync, start_time);
+ assert_eq!(timers.last_announce, start_time);
+ assert_eq!(timers.last_prune, start_time);
+ }
+
+ #[test]
+ fn test_advance_multiple_timers() {
+ let start_time = test_time(1000);
+ let mut timers = TaskTimers::new(start_time);
+
+ let new_time = test_time(2000);
+ let events = vec![
+ TimerEvent::AdvanceIdle(new_time),
+ TimerEvent::AdvanceGossip(new_time),
+ TimerEvent::AdvanceSync(new_time),
+ ];
+
+ timers.advance(&events);
+
+ assert_eq!(timers.last_idle, new_time);
+ assert_eq!(timers.last_gossip, new_time);
+ assert_eq!(timers.last_sync, new_time);
+ assert_eq!(timers.last_announce, start_time);
+ assert_eq!(timers.last_prune, start_time);
+ }
+
+ #[test]
+ fn test_advance_all_timers() {
+ let start_time = test_time(1000);
+ let mut timers = TaskTimers::new(start_time);
+
+ let new_time = test_time(2000);
+ let events = vec![
+ TimerEvent::AdvanceIdle(new_time),
+ TimerEvent::AdvanceGossip(new_time),
+ TimerEvent::AdvanceSync(new_time),
+ TimerEvent::AdvanceAnnounce(new_time),
+ TimerEvent::AdvancePrune(new_time),
+ ];
+
+ timers.advance(&events);
+
+ assert_eq!(timers.last_idle, new_time);
+ assert_eq!(timers.last_gossip, new_time);
+ assert_eq!(timers.last_sync, new_time);
+ assert_eq!(timers.last_announce, new_time);
+ assert_eq!(timers.last_prune, new_time);
+ }
+
+ #[test]
+ fn test_advance_empty_events() {
+ let start_time = test_time(1000);
+ let mut timers = TaskTimers::new(start_time);
+
+ timers.advance(&[]);
+
+ // All timers should remain unchanged
+ assert_eq!(timers.last_idle, start_time);
+ assert_eq!(timers.last_gossip, start_time);
+ assert_eq!(timers.last_sync, start_time);
+ assert_eq!(timers.last_announce, start_time);
+ assert_eq!(timers.last_prune, start_time);
+ }
+
+ #[test]
+ fn test_exactly_at_interval_boundary() {
+ let start_time = test_time(1000);
+ let timers = TaskTimers::new(start_time).with_intervals(Intervals {
+ idle: LocalDuration::from_secs(30),
+ ..Intervals::NEVER
+ });
+
+ // Test exactly at the idle boundary
+ let boundary_time = start_time + test_duration(30);
+ let command = timers.tick(boundary_time);
+
+ assert!(command.tasks.contains(&TaskEvent::Idle(Idle::KeepAlive)));
+ }
+
+ #[test]
+ fn test_just_before_interval_boundary() {
+ let start_time = test_time(1000);
+ // Use different intervals to avoid gossip triggering when testing idle boundary
+ let intervals = Intervals {
+ idle: test_duration(30),
+ ..Intervals::NEVER
+ };
+ let timers = TaskTimers::new(start_time).with_intervals(intervals);
+
+ // Test just before the idle boundary
+ let almost_boundary = start_time + test_duration(29);
+ let command = timers.tick(almost_boundary);
+
+ // Should not trigger idle tasks, only persistent connections
+ assert_tasks(
+ &command.tasks,
+ nonempty![TaskEvent::MaintainPersistentConnections],
+ );
+ }
+
+ #[test]
+ fn test_tick_after_advance() {
+ let start_time = test_time(1000);
+ let mut timers = TaskTimers::new(start_time).with_intervals(Intervals {
+ idle: LocalDuration::from_secs(30),
+ gossip: LocalDuration::from_secs(30),
+ ..Intervals::NEVER
+ });
+
+ // First tick - should trigger idle and gossip
+ let first_tick = start_time + test_duration(30);
+ let command1 = timers.tick(first_tick);
+
+ // Advance the timers
+ timers.advance(&command1.timers);
+
+ // Second tick at same time - should not trigger anything again
+ let command2 = timers.tick(first_tick);
+
+ assert!(!command2.tasks.contains(&TaskEvent::Idle(Idle::KeepAlive)));
+ assert!(!command2
+ .tasks
+ .contains(&TaskEvent::Gossip(Gossip::RelayAnnouncements)));
+ assert_eq!(
+ command2.tasks,
+ nonempty![TaskEvent::MaintainPersistentConnections]
+ );
+ }
+
+ #[test]
+ fn test_tick_advance_tick_cycle() {
+ let start_time = test_time(1000);
+ let mut timers = TaskTimers::new(start_time).with_intervals(Intervals {
+ idle: LocalDuration::from_secs(30),
+ ..Intervals::NEVER
+ });
+
+ // First cycle
+ let tick1 = start_time + test_duration(30);
+ let command1 = timers.tick(tick1);
+ timers.advance(&command1.timers);
+
+ // Second cycle - advance by another idle interval
+ let tick2 = tick1 + test_duration(30);
+ let command2 = timers.tick(tick2);
+
+ // Should trigger idle tasks again
+ assert!(command2.tasks.contains(&TaskEvent::Idle(Idle::KeepAlive)));
+ }
+
+ #[test]
+ fn test_custom_intervals_behavior() {
+ let start_time = test_time(1000);
+ let custom_intervals = Intervals {
+ idle: test_duration(1), // Very short idle interval
+ gossip: test_duration(2), // Short gossip interval
+ ..Intervals::NEVER
+ };
+ let timers = TaskTimers::new(start_time).with_intervals(custom_intervals);
+
+ // Test that custom intervals are respected
+ let tick_time = start_time + test_duration(1);
+ let command = timers.tick(tick_time);
+
+ assert!(command.tasks.contains(&TaskEvent::Idle(Idle::KeepAlive)));
+ // Gossip should not trigger yet (interval is 2s)
+ assert!(!command
+ .tasks
+ .contains(&TaskEvent::Gossip(Gossip::RelayAnnouncements)));
+
+ // Test gossip triggers at its interval
+ let gossip_time = start_time + test_duration(2);
+ let command2 = timers.tick(gossip_time);
+
+ assert!(command2
+ .tasks
+ .contains(&TaskEvent::Gossip(Gossip::RelayAnnouncements)));
+ }
+
+ #[test]
+ fn test_zero_duration_intervals() {
+ let start_time = test_time(1000);
+ let zero_intervals = Intervals {
+ idle: LocalDuration::from_secs(0),
+ gossip: LocalDuration::from_secs(0),
+ ..Intervals::NEVER
+ };
+ let timers = TaskTimers::new(start_time).with_intervals(zero_intervals);
+
+ // Even with zero duration, should trigger immediately
+ let command = timers.tick(start_time);
+
+ assert!(command.tasks.contains(&TaskEvent::Idle(Idle::KeepAlive)));
+ assert!(command
+ .tasks
+ .contains(&TaskEvent::Gossip(Gossip::RelayAnnouncements)));
+ }
+
+ #[test]
+ fn test_partial_timer_advance() {
+ let start_time = test_time(1000);
+ let mut timers = TaskTimers::new(start_time);
+
+ let new_time = test_time(2000);
+
+ // Only advance some timers (not all that might have been generated)
+ let partial_events = vec![
+ TimerEvent::AdvanceIdle(new_time),
+ TimerEvent::AdvanceGossip(new_time),
+ // Intentionally omit sync, announce, and prune
+ ];
+
+ timers.advance(&partial_events);
+
+ // Only idle and gossip should be advanced
+ assert_eq!(timers.last_idle, new_time);
+ assert_eq!(timers.last_gossip, new_time);
+ assert_eq!(timers.last_sync, start_time);
+ assert_eq!(timers.last_announce, start_time);
+ assert_eq!(timers.last_prune, start_time);
+ }
+
+ #[test]
+ fn test_property_timer_monotonicity() {
+ let start_time = test_time(1000);
+ let intervals = Intervals {
+ idle: gen_duration(0),
+ gossip: gen_duration(1),
+ sync: gen_duration(2),
+ announce: gen_duration(3),
+ prune: gen_duration(4),
+ };
+ let mut timers = TaskTimers::new(start_time).with_intervals(intervals);
+
+ let mut current_time = start_time;
+
+ for _ in 0..100 {
+ current_time = current_time + test_duration(10);
+ let command = timers.tick(current_time);
+
+ // Advance all timers
+ timers.advance(&command.timers);
+
+ // Verify all timers are monotonically increasing
+ assert!(timers.last_idle >= start_time);
+ assert!(timers.last_gossip >= start_time);
+ assert!(timers.last_sync >= start_time);
+ assert!(timers.last_announce >= start_time);
+ assert!(timers.last_prune >= start_time);
+ }
+ }
+}
Exit code: 0
shell: 'cargo --version rustc --version cargo fmt --check cargo clippy --all-targets --workspace -- --deny warnings cargo build --all-targets --workspace cargo doc --workspace --no-deps cargo test --workspace --no-fail-fast '
Commands:
$ podman run --name 5b3bf9c2-4f70-48d0-baf7-457d05f42d3d -v /opt/radcis/ci.rad.levitte.org/cci/state/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/s:/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/s:ro -v /opt/radcis/ci.rad.levitte.org/cci/state/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w:/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w -w /5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w -v /opt/radcis/ci.rad.levitte.org/.radicle:/${id}/.radicle:ro -e RAD_HOME=/${id}/.radicle rust:trixie bash /5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/s/script.sh
+ cargo --version
info: syncing channel updates for '1.88-x86_64-unknown-linux-gnu'
info: latest update on 2025-06-26, rust version 1.88.0 (6b00bc388 2025-06-23)
info: downloading component 'cargo'
info: downloading component 'clippy'
info: downloading component 'rust-docs'
info: downloading component 'rust-src'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'rustfmt'
info: installing component 'cargo'
info: installing component 'clippy'
info: installing component 'rust-docs'
info: installing component 'rust-src'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'rustfmt'
cargo 1.88.0 (873a06493 2025-05-10)
+ rustc --version
rustc 1.88.0 (6b00bc388 2025-06-23)
+ cargo fmt --check
+ cargo clippy --all-targets --workspace -- --deny warnings
Updating crates.io index
Downloading crates ...
Downloaded adler2 v2.0.0
Downloaded aead v0.5.2
Downloaded aes v0.8.4
Downloaded getrandom v0.2.15
Downloaded p256 v0.13.2
Downloaded p521 v0.13.3
Downloaded overload v0.1.1
Downloaded aes-gcm v0.10.3
Downloaded fluent-uri v0.3.2
Downloaded p384 v0.13.0
Downloaded smallvec v1.13.2
Downloaded num-traits v0.2.19
Downloaded ssh-encoding v0.2.0
Downloaded systemd-journal-logger v2.2.2
Downloaded scopeguard v1.2.0
Downloaded fxhash v0.2.1
Downloaded referencing v0.30.0
Downloaded syn v1.0.109
Downloaded icu_provider_macros v1.5.0
Downloaded inout v0.1.3
Downloaded signal-hook v0.3.18
Downloaded lexopt v0.3.0
Downloaded multibase v0.9.1
Downloaded ssh-cipher v0.2.0
Downloaded dyn-clone v1.0.17
Downloaded data-encoding-macro v0.1.14
Downloaded base16ct v0.2.0
Downloaded sqlite v0.32.0
Downloaded num-cmp v0.1.0
Downloaded socks5-client v0.4.1
Downloaded write16 v1.0.0
Downloaded matchers v0.1.0
Downloaded signal-hook-mio v0.2.4
Downloaded lazy_static v1.5.0
Downloaded idna_adapter v1.2.0
Downloaded gix-sec v0.10.12
Downloaded yoke-derive v0.7.5
Downloaded icu_locid_transform_data v1.5.1
Downloaded zerofrom v0.1.6
Downloaded tree-sitter-html v0.23.2
Downloaded xattr v1.3.1
Downloaded yoke v0.7.5
Downloaded gix-tempfile v15.0.0
Downloaded normalize-line-endings v0.3.0
Downloaded zeroize v1.7.0
Downloaded nonempty v0.9.0
Downloaded erased-serde v0.4.6
Downloaded noise-framework v0.4.0
Downloaded yansi v0.5.1
Downloaded gix-fs v0.12.1
Downloaded num v0.4.3
Downloaded tempfile v3.10.1
Downloaded utf8_iter v1.0.4
Downloaded itoa v1.0.11
Downloaded test-log-macros v0.2.18
Downloaded gix-lock v15.0.1
Downloaded num-iter v0.1.45
Downloaded crossbeam-utils v0.8.19
Downloaded thiserror v1.0.69
Downloaded tree-sitter-language v0.1.2
Downloaded home v0.5.9
Downloaded gix-revwalk v0.17.0
Downloaded tinyvec_macros v0.1.1
Downloaded gix-hash v0.15.1
Downloaded gix-features v0.39.1
Downloaded gix-negotiate v0.17.0
Downloaded git-ref-format v0.3.1
Downloaded utf8parse v0.2.1
Downloaded test-log v0.2.18
Downloaded gix-quote v0.4.15
Downloaded ghash v0.5.1
Downloaded uuid-simd v0.8.0
Downloaded gix-packetline v0.18.4
Downloaded git-ref-format-macro v0.3.1
Downloaded tree-sitter-toml-ng v0.6.0
Downloaded thiserror v2.0.12
Downloaded jobserver v0.1.31
Downloaded thiserror-impl v1.0.69
Downloaded icu_provider v1.5.0
Downloaded gix-transport v0.44.0
Downloaded hmac v0.12.1
Downloaded unicode-ident v1.0.12
Downloaded icu_normalizer_data v1.5.1
Downloaded icu_normalizer v1.5.0
Downloaded crossterm v0.29.0
Downloaded unicode-segmentation v1.11.0
Downloaded base64 v0.21.7
Downloaded gix-object v0.46.1
Downloaded unicode-normalization v0.1.23
Downloaded mio v0.8.11
Downloaded icu_properties v1.5.1
Downloaded hashbrown v0.14.3
Downloaded gix-pack v0.56.0
Downloaded git2 v0.19.0
Downloaded libm v0.2.8
Downloaded vcpkg v0.2.15
Downloaded idna v1.0.3
Downloaded tree-sitter v0.24.4
Downloaded tracing-subscriber v0.3.19
Downloaded tree-sitter-python v0.23.4
Downloaded chrono v0.4.38
Downloaded tree-sitter-rust v0.23.2
Downloaded bloomy v1.2.0
Downloaded tree-sitter-c v0.23.2
Downloaded aho-corasick v1.1.3
Downloaded tree-sitter-md v0.3.2
Downloaded winnow v0.6.26
Downloaded num-bigint-dig v0.8.4
Downloaded emojis v0.6.4
Downloaded tree-sitter-ruby v0.23.1
Downloaded tree-sitter-bash v0.23.3
Downloaded bstr v1.9.1
Downloaded sha3 v0.10.8
Downloaded tracing v0.1.41
Downloaded icu_collections v1.5.0
Downloaded cyphernet v0.5.2
Downloaded url v2.5.4
Downloaded mio v1.0.4
Downloaded regex-automata v0.4.9
Downloaded jsonschema v0.30.0
Downloaded rustix v1.0.7
Downloaded rustix v0.38.34
Downloaded crossterm v0.25.0
Downloaded bytes v1.10.1
Downloaded libc v0.2.174
Downloaded regex-syntax v0.8.5
Downloaded gix-odb v0.66.0
Downloaded jiff v0.2.1
Downloaded typenum v1.17.0
Downloaded tree-sitter-typescript v0.23.2
Downloaded gix-ref v0.49.1
Downloaded icu_properties_data v1.5.1
Downloaded cc v1.2.2
Downloaded tinyvec v1.6.0
Downloaded fraction v0.15.3
Downloaded derive_more-impl v2.0.1
Downloaded der v0.7.9
Downloaded tracing-core v0.1.34
Downloaded uuid v1.16.0
Downloaded tinystr v0.7.6
Downloaded unicode-width v0.1.11
Downloaded miniz_oxide v0.8.8
Downloaded derive_more v2.0.1
Downloaded timeago v0.4.2
Downloaded flate2 v1.1.1
Downloaded gix-revision v0.31.1
Downloaded gix-refspec v0.27.0
Downloaded base64 v0.13.1
Downloaded gix-actor v0.33.2
Downloaded git-ref-format-core v0.3.1
Downloaded litemap v0.7.5
Downloaded icu_locid v1.5.0
Downloaded crypto-bigint v0.5.5
Downloaded crossbeam-channel v0.5.15
Downloaded iana-time-zone v0.1.60
Downloaded gix-protocol v0.47.0
Downloaded gix-utils v0.1.14
Downloaded memchr v2.7.2
Downloaded gix-commitgraph v0.25.1
Downloaded gix-diff v0.49.0
Downloaded elliptic-curve v0.13.8
Downloaded version_check v0.9.4
Downloaded typeid v1.0.3
Downloaded gix-prompt v0.9.1
Downloaded memmap2 v0.9.4
Downloaded linux-raw-sys v0.4.13
Downloaded regex v1.11.1
Downloaded unicode-display-width v0.3.0
Downloaded gix-traverse v0.43.1
Downloaded gix-url v0.28.2
Downloaded gix-config-value v0.14.12
Downloaded bit-vec v0.8.0
Downloaded gix-credentials v0.26.0
Downloaded num-bigint v0.4.6
Downloaded gix-path v0.10.15
Downloaded zerocopy v0.7.35
Downloaded utf16_iter v1.0.5
Downloaded universal-hash v0.5.1
Downloaded tar v0.4.40
Downloaded lock_api v0.4.11
Downloaded indexmap v2.2.6
Downloaded zerovec v0.10.4
Downloaded litrs v0.4.1
Downloaded libgit2-sys v0.17.0+1.8.1
Downloaded fancy-regex v0.14.0
Downloaded ahash v0.8.11
Downloaded amplify_derive v4.0.0
Downloaded icu_locid_transform v1.5.0
Downloaded diff v0.1.13
Downloaded bitflags v2.9.1
Downloaded gix-hashtable v0.6.0
Downloaded gix-date v0.9.4
Downloaded netservices v0.8.0
Downloaded writeable v0.5.5
Downloaded log v0.4.27
Downloaded num-rational v0.4.2
Downloaded nonempty v0.5.0
Downloaded maybe-async v0.2.10
Downloaded ff v0.13.0
Downloaded amplify v4.6.0
Downloaded newline-converter v0.3.0
Downloaded walkdir v2.5.0
Downloaded tree-sitter-go v0.23.4
Downloaded tracing-log v0.2.0
Downloaded linux-raw-sys v0.9.4
Downloaded inquire v0.7.5
Downloaded gix-command v0.4.1
Downloaded gix-chunk v0.4.11
Downloaded nu-ansi-term v0.46.0
Downloaded localtime v1.3.1
Downloaded regex-automata v0.1.10
Downloaded rand v0.8.5
Downloaded sqlite3-src v0.5.1
Downloaded chacha20poly1305 v0.10.1
Downloaded io-reactor v0.5.2
Downloaded vsimd v0.8.0
Downloaded thiserror-impl v2.0.12
Downloaded cipher v0.4.4
Downloaded blowfish v0.9.1
Downloaded bitflags v1.3.2
Downloaded tree-sitter-css v0.23.1
Downloaded group v0.13.0
Downloaded schemars v1.0.4
Downloaded ppv-lite86 v0.2.17
Downloaded displaydoc v0.2.5
Downloaded digest v0.10.7
Downloaded ctr v0.9.2
Downloaded chacha20 v0.9.1
Downloaded autocfg v1.2.0
Downloaded num-integer v0.1.46
Downloaded rsa v0.9.6
Downloaded crc32fast v1.4.0
Downloaded prodash v29.0.2
Downloaded ecdsa v0.16.9
Downloaded thread_local v1.1.9
Downloaded num-complex v0.4.6
Downloaded signals_receipts v0.2.0
Downloaded env_logger v0.11.8
Downloaded ec25519 v0.1.0
Downloaded synstructure v0.13.1
Downloaded syn v2.0.89
Downloaded ssh-key v0.6.6
Downloaded parking_lot v0.12.3
Downloaded bytesize v2.0.1
Downloaded socket2 v0.5.7
Downloaded tree-sitter-highlight v0.24.4
Downloaded keccak v0.1.5
Downloaded serde v1.0.219
Downloaded zerovec-derive v0.10.3
Downloaded sec1 v0.7.3
Downloaded pem-rfc7468 v0.7.0
Downloaded gix-trace v0.1.12
Downloaded gix-shallow v0.1.0
Downloaded zerofrom-derive v0.1.6
Downloaded tree-sitter-json v0.24.8
Downloaded data-encoding v2.5.0
Downloaded const-oid v0.9.6
Downloaded amplify_num v0.5.2
Downloaded escargot v0.5.10
Downloaded either v1.11.0
Downloaded colored v2.1.0
Downloaded anyhow v1.0.82
Downloaded fastrand v2.1.0
Downloaded snapbox-macros v0.3.8
Downloaded shlex v1.3.0
Downloaded pretty_assertions v1.4.0
Downloaded phf_shared v0.11.3
Downloaded errno v0.3.13
Downloaded block-buffer v0.10.4
Downloaded gix-validate v0.9.4
Downloaded serde_derive v1.0.219
Downloaded salsa20 v0.10.2
Downloaded form_urlencoded v1.2.1
Downloaded equivalent v1.0.1
Downloaded env_filter v0.1.3
Downloaded document-features v0.2.11
Downloaded data-encoding-macro-internal v0.1.12
Downloaded convert_case v0.7.1
Downloaded phf v0.11.3
Downloaded pbkdf2 v0.12.2
Downloaded ct-codecs v1.1.1
Downloaded pkcs1 v0.7.5
Downloaded generic-array v0.14.7
Downloaded cyphergraphy v0.3.0
Downloaded borrow-or-share v0.2.2
Downloaded bit-set v0.8.0
Downloaded streaming-iterator v0.1.9
Downloaded ref-cast v1.0.24
Downloaded rand_core v0.6.4
Downloaded radicle-git-ext v0.8.1
Downloaded primeorder v0.13.6
Downloaded popol v3.0.0
Downloaded pkg-config v0.3.30
Downloaded cypheraddr v0.4.0
Downloaded ref-cast-impl v1.0.24
Downloaded spin v0.9.8
Downloaded sha2 v0.10.8
Downloaded ryu v1.0.17
Downloaded qcheck-macros v1.0.0
Downloaded libz-sys v1.1.16
Downloaded qcheck v1.0.0
Downloaded proc-macro2 v1.0.92
Downloaded polyval v0.6.2
Downloaded pin-project-lite v0.2.16
Downloaded percent-encoding v2.3.1
Downloaded base64 v0.22.1
Downloaded arc-swap v1.7.1
Downloaded subtle v2.5.0
Downloaded spki v0.7.3
Downloaded snapbox v0.4.17
Downloaded siphasher v1.0.1
Downloaded siphasher v0.3.11
Downloaded similar v2.5.0
Downloaded signature v1.6.4
Downloaded sharded-slab v0.1.7
Downloaded serde_json v1.0.140
Downloaded sem_safe v0.2.0
Downloaded scrypt v0.11.0
Downloaded schemars_derive v1.0.4
Downloaded same-file v1.0.6
Downloaded rfc6979 v0.4.0
Downloaded rand_chacha v0.3.1
Downloaded proc-macro-error-attr v1.0.4
Downloaded cbc v0.1.2
Downloaded bytecount v0.6.8
Downloaded regex-syntax v0.6.29
Downloaded proc-macro-error v1.0.4
Downloaded byteorder v1.5.0
Downloaded base64ct v1.6.0
Downloaded quote v1.0.36
Downloaded bcrypt-pbkdf v0.10.0
Downloaded stable_deref_trait v1.2.0
Downloaded signature v2.2.0
Downloaded shell-words v1.1.0
Downloaded serde-untagged v0.1.7
Downloaded poly1305 v0.8.0
Downloaded pkcs8 v0.10.2
Downloaded parking_lot_core v0.9.9
Downloaded filetime v0.2.23
Downloaded faster-hex v0.9.0
Downloaded ed25519 v1.5.3
Downloaded base32 v0.4.0
Downloaded ascii v1.1.0
Downloaded anstyle-query v1.0.2
Downloaded anstream v0.6.13
Downloaded sqlite3-sys v0.15.2
Downloaded sha1_smol v1.0.0
Downloaded serde_derive_internals v0.29.1
Downloaded radicle-surf v0.22.0
Downloaded fast-glob v0.3.3
Downloaded crypto-common v0.1.6
Downloaded cpufeatures v0.2.12
Downloaded cfg-if v1.0.0
Downloaded block-padding v0.3.3
Downloaded amplify_syn v2.0.1
Downloaded anstyle v1.0.6
Downloaded signal-hook-registry v1.4.5
Downloaded radicle-std-ext v0.1.0
Downloaded base-x v0.2.11
Downloaded email_address v0.2.9
Downloaded colorchoice v1.0.0
Downloaded anstyle-parse v0.2.3
Downloaded opaque-debug v0.3.1
Downloaded once_cell v1.21.3
Downloaded outref v0.5.2
Compiling libc v0.2.174
Compiling proc-macro2 v1.0.92
Compiling unicode-ident v1.0.12
Checking cfg-if v1.0.0
Compiling shlex v1.3.0
Compiling version_check v0.9.4
Compiling serde v1.0.219
Checking memchr v2.7.2
Compiling quote v1.0.36
Compiling jobserver v0.1.31
Compiling autocfg v1.2.0
Checking getrandom v0.2.15
Compiling syn v2.0.89
Checking smallvec v1.13.2
Compiling cc v1.2.2
Checking log v0.4.27
Checking aho-corasick v1.1.3
Compiling typenum v1.17.0
Checking regex-syntax v0.8.5
Compiling generic-array v0.14.7
Checking rand_core v0.6.4
Checking fastrand v2.1.0
Checking bitflags v2.9.1
Checking regex-automata v0.4.9
Compiling lock_api v0.4.11
Compiling parking_lot_core v0.9.9
Checking crypto-common v0.1.6
Checking scopeguard v1.2.0
Checking stable_deref_trait v1.2.0
Checking subtle v2.5.0
Checking parking_lot v0.12.3
Checking once_cell v1.21.3
Compiling syn v1.0.109
Checking tinyvec_macros v0.1.1
Checking tinyvec v1.6.0
Checking zeroize v1.7.0
Compiling synstructure v0.13.1
Checking unicode-normalization v0.1.23
Checking bstr v1.9.1
Checking cpufeatures v0.2.12
Checking litemap v0.7.5
Checking writeable v0.5.5
Compiling icu_locid_transform_data v1.5.1
Compiling crc32fast v1.4.0
Compiling thiserror v2.0.12
Compiling serde_derive v1.0.219
Compiling zerofrom-derive v0.1.6
Compiling yoke-derive v0.7.5
Compiling zerovec-derive v0.10.3
Compiling displaydoc v0.2.5
Checking zerofrom v0.1.6
Checking yoke v0.7.5
Compiling thiserror-impl v2.0.12
Compiling icu_provider_macros v1.5.0
Checking zerovec v0.10.4
Checking tinystr v0.7.6
Checking block-padding v0.3.3
Checking icu_locid v1.5.0
Compiling icu_properties_data v1.5.1
Checking inout v0.1.3
Checking block-buffer v0.10.4
Compiling icu_normalizer_data v1.5.1
Compiling pkg-config v0.3.30
Checking icu_provider v1.5.0
Checking hashbrown v0.14.3
Checking itoa v1.0.11
Checking icu_locid_transform v1.5.0
Checking digest v0.10.7
Checking cipher v0.4.4
Checking icu_collections v1.5.0
Compiling thiserror v1.0.69
Checking utf16_iter v1.0.5
Checking write16 v1.0.0
Checking utf8_iter v1.0.4
Compiling thiserror-impl v1.0.69
Checking percent-encoding v2.3.1
Checking icu_properties v1.5.1
Compiling rustix v0.38.34
Checking linux-raw-sys v0.4.13
Checking sha2 v0.10.8
Checking form_urlencoded v1.2.1
Checking universal-hash v0.5.1
Compiling vcpkg v0.2.15
Checking opaque-debug v0.3.1
Compiling libz-sys v1.1.16
Compiling amplify_syn v2.0.1
Checking gix-trace v0.1.12
Compiling data-encoding v2.5.0
Checking icu_normalizer v1.5.0
Checking tempfile v3.10.1
Checking idna_adapter v1.2.0
Checking idna v1.0.3
Compiling data-encoding-macro-internal v0.1.12
Checking signature v1.6.4
Compiling amplify_derive v4.0.0
Checking url v2.5.4
Checking ascii v1.1.0
Checking amplify_num v0.5.2
Checking data-encoding-macro v0.1.14
Checking ed25519 v1.5.3
Checking faster-hex v0.9.0
Compiling libgit2-sys v0.17.0+1.8.1
Checking aead v0.5.2
Compiling num-traits v0.2.19
Compiling proc-macro-error-attr v1.0.4
Checking ct-codecs v1.1.1
Checking base-x v0.2.11
Checking byteorder v1.5.0
Checking multibase v0.9.1
Checking ec25519 v0.1.0
Checking poly1305 v0.8.0
Checking chacha20 v0.9.1
Checking gix-utils v0.1.14
Compiling proc-macro-error v1.0.4
Checking adler2 v2.0.0
Checking miniz_oxide v0.8.8
Checking amplify v4.6.0
Checking cyphergraphy v0.3.0
Checking gix-hash v0.15.1
Checking same-file v1.0.6
Compiling crossbeam-utils v0.8.19
Checking keccak v0.1.5
Checking flate2 v1.1.1
Checking sha3 v0.10.8
Checking walkdir v2.5.0
Compiling git-ref-format-core v0.3.1
Checking polyval v0.6.2
Checking hmac v0.12.1
Compiling sqlite3-src v0.5.1
Checking prodash v29.0.2
Compiling serde_json v1.0.140
Checking base64ct v1.6.0
Checking base32 v0.4.0
Checking equivalent v1.0.1
Checking sha1_smol v1.0.0
Checking ppv-lite86 v0.2.17
Checking pem-rfc7468 v0.7.0
Checking gix-features v0.39.1
Checking cypheraddr v0.4.0
Checking indexmap v2.2.6
Checking rand_chacha v0.3.1
Checking pbkdf2 v0.12.2
Compiling git-ref-format-macro v0.3.1
Checking ghash v0.5.1
Checking chacha20poly1305 v0.10.1
Checking ctr v0.9.2
Checking aes v0.8.4
Checking ryu v1.0.17
Checking aes-gcm v0.10.3
Checking git-ref-format v0.3.1
Checking noise-framework v0.4.0
Checking crossbeam-channel v0.5.15
Checking rand v0.8.5
Checking socks5-client v0.4.1
Checking ssh-encoding v0.2.0
Checking blowfish v0.9.1
Checking cbc v0.1.2
Checking home v0.5.9
Checking radicle-std-ext v0.1.0
Compiling ref-cast v1.0.24
Checking gix-path v0.10.15
Checking ssh-cipher v0.2.0
Checking bcrypt-pbkdf v0.10.0
Checking cyphernet v0.5.2
Compiling ref-cast-impl v1.0.24
Checking signature v2.2.0
Checking ssh-key v0.6.6
Checking qcheck v1.0.0
Checking radicle-ssh v0.10.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle-ssh)
Checking dyn-clone v1.0.17
Compiling typeid v1.0.3
Checking lazy_static v1.5.0
Checking siphasher v1.0.1
Checking nonempty v0.9.0
Compiling serde_derive_internals v0.29.1
Checking radicle-dag v0.10.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle-dag)
Checking erased-serde v0.4.6
Checking iana-time-zone v0.1.60
Checking jiff v0.2.1
Compiling schemars_derive v1.0.4
Checking gix-date v0.9.4
Checking chrono v0.4.38
Checking schemars v1.0.4
Checking serde-untagged v0.1.7
Checking colored v2.1.0
Checking bytesize v2.0.1
Checking localtime v1.3.1
Checking winnow v0.6.26
Checking tree-sitter-language v0.1.2
Checking fast-glob v0.3.3
Checking base64 v0.21.7
Checking gix-hashtable v0.6.0
Checking gix-validate v0.9.4
Checking anstyle-query v1.0.2
Checking memmap2 v0.9.4
Compiling rustix v1.0.7
Compiling anyhow v1.0.82
Checking gix-actor v0.33.2
Checking gix-object v0.46.1
Checking gix-chunk v0.4.11
Checking linux-raw-sys v0.9.4
Checking gix-commitgraph v0.25.1
Checking gix-revwalk v0.17.0
Checking gix-fs v0.12.1
Checking sem_safe v0.2.0
Checking errno v0.3.13
Checking signals_receipts v0.2.0
Checking gix-tempfile v15.0.0
Compiling signal-hook v0.3.18
Checking signal-hook-registry v1.4.5
Checking shell-words v1.1.0
Checking gix-command v0.4.1
Checking radicle-signals v0.11.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle-signals)
Compiling tree-sitter v0.24.4
Checking mio v0.8.11
Checking mio v1.0.4
Compiling unicode-segmentation v1.11.0
Checking utf8parse v0.2.1
Checking anstyle-parse v0.2.3
Compiling convert_case v0.7.1
Checking signal-hook-mio v0.2.4
Checking gix-lock v15.0.1
Checking gix-config-value v0.14.12
Checking gix-url v0.28.2
Checking gix-quote v0.4.15
Checking regex v1.11.1
Checking gix-sec v0.10.12
Checking colorchoice v1.0.0
Checking anstyle v1.0.6
Checking anstream v0.6.13
Checking gix-prompt v0.9.1
Compiling xattr v1.3.1
Compiling derive_more-impl v2.0.1
Compiling filetime v0.2.23
Checking gix-traverse v0.43.1
Checking gix-revision v0.31.1
Checking gix-diff v0.49.0
Checking gix-packetline v0.18.4
Compiling litrs v0.4.1
Checking lexopt v0.3.0
Checking bitflags v1.3.2
Compiling document-features v0.2.11
Checking crossterm v0.25.0
Checking gix-transport v0.44.0
Checking gix-refspec v0.27.0
Checking gix-pack v0.56.0
Checking derive_more v2.0.1
Compiling tar v0.4.40
Checking gix-credentials v0.26.0
Checking newline-converter v0.3.0
Checking gix-ref v0.49.1
Checking gix-shallow v0.1.0
Checking gix-negotiate v0.17.0
Checking fxhash v0.2.1
Compiling maybe-async v0.2.10
Checking arc-swap v1.7.1
Checking streaming-iterator v0.1.9
Checking sqlite3-sys v0.15.2
Checking unicode-width v0.1.11
Checking sqlite v0.32.0
Checking inquire v0.7.5
Checking gix-protocol v0.47.0
Checking gix-odb v0.66.0
Compiling radicle-surf v0.22.0
Checking crossterm v0.29.0
Checking unicode-display-width v0.3.0
Compiling tree-sitter-c v0.23.2
Compiling tree-sitter-ruby v0.23.1
Compiling tree-sitter-typescript v0.23.2
Compiling tree-sitter-go v0.23.4
Compiling tree-sitter-md v0.3.2
Compiling tree-sitter-toml-ng v0.6.0
Compiling tree-sitter-json v0.24.8
Compiling tree-sitter-rust v0.23.2
Compiling tree-sitter-css v0.23.1
Compiling tree-sitter-html v0.23.2
Compiling tree-sitter-bash v0.23.3
Compiling tree-sitter-python v0.23.4
Checking either v1.11.0
Checking snapbox-macros v0.3.8
Checking salsa20 v0.10.2
Checking nonempty v0.5.0
Checking similar v2.5.0
Checking siphasher v0.3.11
Checking normalize-line-endings v0.3.0
Checking base64 v0.13.1
Compiling radicle-cli v0.15.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle-cli)
Checking snapbox v0.4.17
Checking bloomy v1.2.0
Checking scrypt v0.11.0
Checking tree-sitter-highlight v0.24.4
Checking systemd-journal-logger v2.2.2
Checking popol v3.0.0
Checking timeago v0.4.2
Checking bytes v1.10.1
Checking io-reactor v0.5.2
Checking socket2 v0.5.7
Checking yansi v0.5.1
Checking diff v0.1.13
Compiling radicle-node v0.14.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle-node)
Checking pretty_assertions v1.4.0
Checking netservices v0.8.0
Checking radicle-systemd v0.10.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle-systemd)
Checking num-integer v0.1.46
Compiling escargot v0.5.10
Compiling qcheck-macros v1.0.0
Checking num-bigint v0.4.6
Compiling ahash v0.8.11
Compiling radicle-remote-helper v0.12.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle-remote-helper)
Checking num-iter v0.1.45
Checking num-rational v0.4.2
Checking num-complex v0.4.6
Checking env_filter v0.1.3
Checking zerocopy v0.7.35
Checking borrow-or-share v0.2.2
Checking bit-vec v0.8.0
Checking num v0.4.3
Checking fluent-uri v0.3.2
Checking bit-set v0.8.0
Checking env_logger v0.11.8
Checking phf_shared v0.11.3
Compiling test-log-macros v0.2.18
Checking vsimd v0.8.0
Checking uuid v1.16.0
Checking outref v0.5.2
Checking referencing v0.30.0
Checking uuid-simd v0.8.0
Checking test-log v0.2.18
Checking phf v0.11.3
Checking fancy-regex v0.14.0
Checking fraction v0.15.3
Checking email_address v0.2.9
Checking base64 v0.22.1
Checking bytecount v0.6.8
Checking num-cmp v0.1.0
Checking emojis v0.6.4
Checking jsonschema v0.30.0
Checking git2 v0.19.0
Checking radicle-git-ext v0.8.1
Checking radicle-term v0.14.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle-term)
Checking radicle-crypto v0.13.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle-crypto)
Checking radicle-cob v0.15.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle-cob)
Checking radicle v0.18.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle)
Checking radicle-fetch v0.14.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle-fetch)
Checking radicle-cli-test v0.12.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle-cli-test)
Checking radicle-schemars v0.4.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle-schemars)
Checking radicle-protocol v0.2.0 (/5b3bf9c2-4f70-48d0-baf7-457d05f42d3d/w/crates/radicle-protocol)
error: variables can be used directly in the `format!` string
--> crates/radicle-protocol/src/tasks.rs:396:9
|
396 | / assert_eq!(
397 | | got.len(),
398 | | expected.len(),
399 | | "extra task(s) emitted: {:?}",
400 | | got
401 | | );
| |_________^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#uninlined_format_args
= note: `-D clippy::uninlined-format-args` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::uninlined_format_args)]`
error: variables can be used directly in the `format!` string
--> crates/radicle-protocol/src/tasks.rs:408:9
|
408 | / assert_eq!(
409 | | got.len(),
410 | | expected.len(),
411 | | "extra timer(s) emitted: {:?}",
412 | | got
413 | | );
| |_________^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#uninlined_format_args
error: could not compile `radicle-protocol` (lib test) due to 2 previous errors
warning: build failed, waiting for other jobs to finish...
Exit code: 101
{
"response": "finished",
"result": "failure"
}