Skip to content

Commit

Permalink
refactor(autonomi): deprecate connect; docs
Browse files Browse the repository at this point in the history
refactor(autonomi): simplify init
  • Loading branch information
b-zee committed Dec 16, 2024
1 parent 1061abc commit 25be50f
Show file tree
Hide file tree
Showing 10 changed files with 60 additions and 37 deletions.
2 changes: 1 addition & 1 deletion ant-cli/src/actions/connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub async fn connect_to_network(peers: Vec<Multiaddr>) -> Result<Client> {

progress_bar.set_message("Connecting to The Autonomi Network...");

match Client::connect(&peers).await {
match Client::init_with_peers(peers).await {
Ok(client) => {
info!("Connected to the Network");
progress_bar.finish_with_message("Connected to the Network");
Expand Down
2 changes: 1 addition & 1 deletion ant-node/tests/common/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ impl LocalNetwork {

println!("Client bootstrap with peer {bootstrap_peers:?}");
info!("Client bootstrap with peer {bootstrap_peers:?}");
Client::connect(&bootstrap_peers)
Client::init_with_peers(bootstrap_peers)
.await
.expect("Client shall be successfully created.")
}
Expand Down
2 changes: 1 addition & 1 deletion autonomi/examples/put_and_dir_upload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Default wallet of testnet.
let key = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";

let client = Client::connect(&["/ip4/127.0.0.1/udp/1234/quic-v1".parse()?]).await?;
let client = Client::init_local().await?;
let wallet = Wallet::new_from_private_key(Default::default(), key)?;

// Put and fetch data.
Expand Down
55 changes: 40 additions & 15 deletions autonomi/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub use ant_evm::Amount;

use ant_evm::EvmNetwork;
use ant_networking::{interval, multiaddr_is_global, Network, NetworkBuilder, NetworkEvent};
use ant_protocol::{version::IDENTIFY_PROTOCOL_STR, CLOSE_GROUP_SIZE};
use ant_protocol::version::IDENTIFY_PROTOCOL_STR;
use libp2p::{identity::Keypair, Multiaddr};
use std::{collections::HashSet, sync::Arc, time::Duration};
use tokio::sync::mpsc;
Expand All @@ -49,7 +49,10 @@ pub const CONNECT_TIMEOUT_SECS: u64 = 10;

const CLIENT_EVENT_CHANNEL_SIZE: usize = 100;

/// Represents a connection to the Autonomi network.
// Amount of peers to confirm into our routing table before we consider the client ready.
pub use ant_protocol::CLOSE_GROUP_SIZE;

/// Represents a client for the Autonomi network.
///
/// # Example
///
Expand Down Expand Up @@ -82,25 +85,15 @@ pub struct ClientConfig {
pub peers: Option<Vec<Multiaddr>>,
}

impl ClientConfig {
/// Get a configuration for a local client.
pub fn local() -> Self {
Self {
local: true,
..Default::default()
}
}
}

/// Error returned by [`Client::connect`].
#[derive(Debug, thiserror::Error)]
pub enum ConnectError {
/// Did not manage to connect to enough peers in time.
#[error("Could not connect to enough peers in time.")]
/// Did not manage to populate the routing table with enough peers.
#[error("Failed to populate our routing table with enough peers in time")]
TimedOut,

/// Same as [`ConnectError::TimedOut`] but with a list of incompatible protocols.
#[error("Could not connect to peers due to incompatible protocol: {0:?}")]
#[error("Failed to populate our routing table due to incompatible protocol: {0:?}")]
TimedOutWithIncompatibleProtocol(HashSet<String>, String),

/// An error occurred while bootstrapping the client.
Expand All @@ -116,10 +109,42 @@ impl Client {
Self::init_with_config(Default::default()).await
}

/// Initialize a client that is configured to be local.
///
/// See [`Client::init_with_config`].
pub async fn init_local() -> Result<Self, ConnectError> {
Self::init_with_config(ClientConfig {
local: true,
..Default::default()
})
.await
}

/// Initialize a client that bootstraps from a list of peers.
///
/// If any of the provided peers is a global address, the client will not be local.
///
/// ```no_run
/// // Will set `local` to true.
/// let client = Client::init_with_peers(vec!["/ip4/127.0.0.1/udp/1234/quic-v1".parse()?]).await?;
/// ```
pub async fn init_with_peers(peers: Vec<Multiaddr>) -> Result<Self, ConnectError> {
// Any global address makes the client non-local
let local = !peers.iter().any(multiaddr_is_global);

Self::init_with_config(ClientConfig {
local,
peers: Some(peers),
})
.await
}

/// Initialize the client with the given configuration.
///
/// This will block until [`CLOSE_GROUP_SIZE`] have been added to the routing table.
///
/// See [`ClientConfig`].
///
/// ```no_run
/// use autonomi::client::Client;
/// # #[tokio::main]
Expand Down
8 changes: 5 additions & 3 deletions autonomi/src/python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ impl PyClient {
pyo3::exceptions::PyValueError::new_err(format!("Invalid multiaddr: {e}"))
})?;

let client = rt.block_on(RustClient::connect(&peers)).map_err(|e| {
pyo3::exceptions::PyValueError::new_err(format!("Failed to connect: {e}"))
})?;
let client = rt
.block_on(RustClient::init_with_peers(peers))
.map_err(|e| {
pyo3::exceptions::PyValueError::new_err(format!("Failed to connect: {e}"))
})?;

Ok(Self { inner: client })
}
Expand Down
4 changes: 2 additions & 2 deletions autonomi/tests/external_signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use bytes::Bytes;
use std::collections::BTreeMap;
use std::time::Duration;
use test_utils::evm::get_funded_wallet;
use test_utils::{gen_random_data, peers_from_env};
use test_utils::gen_random_data;
use tokio::time::sleep;
use xor_name::XorName;

Expand Down Expand Up @@ -103,7 +103,7 @@ async fn external_signer_put() -> eyre::Result<()> {
let _log_appender_guard =
LogBuilder::init_single_threaded_tokio_test("external_signer_put", false);

let client = Client::connect(&peers_from_env()?).await?;
let client = Client::init_local().await?;
let wallet = get_funded_wallet();
let data = gen_random_data(1024 * 1024 * 10);

Expand Down
8 changes: 4 additions & 4 deletions autonomi/tests/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use sha2::{Digest, Sha256};
use std::fs::File;
use std::io::{BufReader, Read};
use std::time::Duration;
use test_utils::{evm::get_funded_wallet, peers_from_env};
use test_utils::evm::get_funded_wallet;
use tokio::time::sleep;
use walkdir::WalkDir;

Expand All @@ -26,7 +26,7 @@ async fn dir_upload_download() -> Result<()> {
let _log_appender_guard =
LogBuilder::init_single_threaded_tokio_test("dir_upload_download", false);

let client = Client::connect(&peers_from_env()?).await?;
let client = Client::init_local().await?;
let wallet = get_funded_wallet();

let addr = client
Expand Down Expand Up @@ -81,7 +81,7 @@ fn compute_dir_sha256(dir: &str) -> Result<String> {
async fn file_into_vault() -> Result<()> {
let _log_appender_guard = LogBuilder::init_single_threaded_tokio_test("file", false);

let client = Client::connect(&peers_from_env()?).await?;
let client = Client::init_local().await?;
let wallet = get_funded_wallet();
let client_sk = bls::SecretKey::random();

Expand All @@ -102,7 +102,7 @@ async fn file_into_vault() -> Result<()> {
.await?;

// now assert over the stored account packet
let new_client = Client::connect(&[]).await?;
let new_client = Client::init_local().await?;

let (ap, got_version) = new_client.fetch_and_decrypt_vault(&client_sk).await?;
assert_eq!(set_version, got_version);
Expand Down
8 changes: 2 additions & 6 deletions autonomi/tests/put.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,15 @@
// permissions and limitations relating to use of the SAFE Network Software.

use ant_logging::LogBuilder;
use autonomi::{client::ClientConfig, Client};
use autonomi::Client;
use eyre::Result;
use test_utils::{evm::get_funded_wallet, gen_random_data};

#[tokio::test]
async fn put() -> Result<()> {
let _log_appender_guard = LogBuilder::init_single_threaded_tokio_test("put", false);

let client = Client::init_with_config(ClientConfig {
local: true,
..Default::default()
})
.await?;
let client = Client::init_local().await?;
let wallet = get_funded_wallet();
let data = gen_random_data(1024 * 1024 * 10);

Expand Down
4 changes: 2 additions & 2 deletions autonomi/tests/register.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ use bytes::Bytes;
use eyre::Result;
use rand::Rng;
use std::time::Duration;
use test_utils::{evm::get_funded_wallet, peers_from_env};
use test_utils::evm::get_funded_wallet;
use tokio::time::sleep;

#[tokio::test]
async fn register() -> Result<()> {
let _log_appender_guard = LogBuilder::init_single_threaded_tokio_test("register", false);

let client = Client::connect(&peers_from_env()?).await?;
let client = Client::init_local().await?;
let wallet = get_funded_wallet();

// Owner key of the register.
Expand Down
4 changes: 2 additions & 2 deletions autonomi/tests/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ use ant_logging::LogBuilder;
use ant_protocol::storage::Transaction;
use autonomi::{client::transactions::TransactionError, Client};
use eyre::Result;
use test_utils::{evm::get_funded_wallet, peers_from_env};
use test_utils::evm::get_funded_wallet;

#[tokio::test]
async fn transaction_put() -> Result<()> {
let _log_appender_guard = LogBuilder::init_single_threaded_tokio_test("transaction", false);

let client = Client::connect(&peers_from_env()?).await?;
let client = Client::init_local().await?;
let wallet = get_funded_wallet();

let key = bls::SecretKey::random();
Expand Down

0 comments on commit 25be50f

Please sign in to comment.