Skip to content

Commit

Permalink
refactor(autonomi): deprecate connect; docs
Browse files Browse the repository at this point in the history
  • Loading branch information
b-zee committed Dec 16, 2024
1 parent 1061abc commit 0f90a9e
Show file tree
Hide file tree
Showing 9 changed files with 63 additions and 34 deletions.
3 changes: 2 additions & 1 deletion ant-cli/src/actions/connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
// permissions and limitations relating to use of the SAFE Network Software.

use autonomi::Client;
use autonomi::ClientConfig;
use autonomi::Multiaddr;
use color_eyre::eyre::bail;
use color_eyre::eyre::Result;
Expand All @@ -22,7 +23,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_config(ClientConfig::from_peers(peers)).await {
Ok(client) => {
info!("Connected to the Network");
progress_bar.finish_with_message("Connected to the Network");
Expand Down
4 changes: 2 additions & 2 deletions ant-node/tests/common/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
use ant_evm::Amount;
use ant_protocol::antnode_proto::{NodeInfoRequest, RestartRequest};
use ant_service_management::{get_local_node_registry_path, NodeRegistry};
use autonomi::Client;
use autonomi::{Client, ClientConfig};
use evmlib::wallet::Wallet;
use eyre::Result;
use std::str::FromStr;
Expand Down 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_config(ClientConfig::from_peers(bootstrap_peers))
.await
.expect("Client shall be successfully created.")
}
Expand Down
4 changes: 2 additions & 2 deletions autonomi/examples/put_and_dir_upload.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use autonomi::{Bytes, Client, Wallet};
use autonomi::{Bytes, Client, ClientConfig, Wallet};

#[tokio::main]
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_with_config(ClientConfig::local()).await?;
let wallet = Wallet::new_from_private_key(Default::default(), key)?;

// Put and fetch data.
Expand Down
33 changes: 27 additions & 6 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 @@ -83,24 +86,42 @@ pub struct ClientConfig {
}

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

/// Configuration for 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 config = autonomi::ClientConfig::from_peers(vec!["/ip4/127.0.0.1/udp/1234/quic-v1".parse()?]);
/// ```
pub fn from_peers(peers: Vec<Multiaddr>) -> Self {
// Any global address makes the client non-local
let local = !peers.iter().any(multiaddr_is_global);

Self {
local,
peers: Some(peers),
}
}
}

/// 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 Down
25 changes: 16 additions & 9 deletions autonomi/src/python.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
// TODO: Shall be removed once the python binding warnings resolved
#![allow(non_local_definitions)]

use crate::client::{
data::DataMapChunk,
files::{archive::PrivateArchiveAccess, archive_public::ArchiveAddr},
payment::PaymentOption as RustPaymentOption,
vault::{UserData, VaultSecretKey},
Client as RustClient,
use crate::{
client::{
data::DataMapChunk,
files::{archive::PrivateArchiveAccess, archive_public::ArchiveAddr},
payment::PaymentOption as RustPaymentOption,
vault::{UserData, VaultSecretKey},
Client as RustClient,
},
ClientConfig,
};
use crate::{Bytes, Network, Wallet as RustWallet};
use pyo3::exceptions::PyValueError;
Expand All @@ -31,9 +34,13 @@ 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_config(ClientConfig::from_peers(
peers,
)))
.map_err(|e| {
pyo3::exceptions::PyValueError::new_err(format!("Failed to connect: {e}"))
})?;

Ok(Self { inner: client })
}
Expand Down
6 changes: 3 additions & 3 deletions autonomi/tests/external_signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ use autonomi::client::payment::{receipt_from_store_quotes, Receipt};
use autonomi::client::quote::StoreQuote;
use autonomi::client::vault::user_data::USER_DATA_VAULT_CONTENT_IDENTIFIER;
use autonomi::client::vault::VaultSecretKey;
use autonomi::{Client, Wallet};
use autonomi::{Client, ClientConfig, Wallet};
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_with_config(ClientConfig::local()).await?;
let wallet = get_funded_wallet();
let data = gen_random_data(1024 * 1024 * 10);

Expand Down
10 changes: 5 additions & 5 deletions autonomi/tests/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
#![cfg(feature = "fs")]

use ant_logging::LogBuilder;
use autonomi::Client;
use autonomi::{Client, ClientConfig};
use eyre::Result;
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_with_config(ClientConfig::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_with_config(ClientConfig::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_with_config(ClientConfig::local()).await?;

let (ap, got_version) = new_client.fetch_and_decrypt_vault(&client_sk).await?;
assert_eq!(set_version, got_version);
Expand Down
6 changes: 3 additions & 3 deletions autonomi/tests/register.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,19 @@
#![cfg(feature = "registers")]

use ant_logging::LogBuilder;
use autonomi::Client;
use autonomi::{Client, ClientConfig};
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_with_config(ClientConfig::local()).await?;
let wallet = get_funded_wallet();

// Owner key of the register.
Expand Down
6 changes: 3 additions & 3 deletions autonomi/tests/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@

use ant_logging::LogBuilder;
use ant_protocol::storage::Transaction;
use autonomi::{client::transactions::TransactionError, Client};
use autonomi::{client::transactions::TransactionError, Client, ClientConfig};
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_with_config(ClientConfig::local()).await?;
let wallet = get_funded_wallet();

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

0 comments on commit 0f90a9e

Please sign in to comment.