Skip to content

Commit

Permalink
chore: Remove Bitswap prefix from all names (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
oblique authored Jan 30, 2024
1 parent 914452f commit 64e65d5
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 86 deletions.
43 changes: 20 additions & 23 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,19 @@ use blockstore::Blockstore;
use crate::client::{ClientBehaviour, ClientConfig};
use crate::multihasher::{Multihasher, MultihasherTable};
use crate::utils::stream_protocol;
use crate::{BitswapBehaviour, BitswapError, Result};
use crate::{Behaviour, Error, Result};

/// Builder for [`BitswapBehaviour`].
/// Builder for [`Behaviour`].
///
/// # Example
///
/// ```rust,no_run
/// # use blockstore::InMemoryBlockstore;
/// # use beetswap::BitswapBehaviour;
/// # fn new() -> BitswapBehaviour<64, InMemoryBlockstore<64>> {
/// BitswapBehaviour::builder(InMemoryBlockstore::new())
/// # fn new() -> beetswap::Behaviour<64, InMemoryBlockstore<64>> {
/// beetswap::Behaviour::builder(InMemoryBlockstore::new())
/// .build()
/// # }
pub struct BitswapBehaviourBuilder<const S: usize, B>
pub struct BehaviourBuilder<const S: usize, B>
where
B: Blockstore + Send + Sync + 'static,
{
Expand All @@ -28,13 +27,13 @@ where
multihasher: MultihasherTable<S>,
}

impl<const S: usize, B> BitswapBehaviourBuilder<S, B>
impl<const S: usize, B> BehaviourBuilder<S, B>
where
B: Blockstore + Send + Sync + 'static,
{
/// Creates a new builder for [`BitswapBehaviour`].
/// Creates a new builder for [`Behaviour`].
pub(crate) fn new(blockstore: B) -> Self {
BitswapBehaviourBuilder {
BehaviourBuilder {
protocol_prefix: None,
blockstore,
client: ClientConfig {
Expand All @@ -56,18 +55,17 @@ where
///
/// ```rust,no_run
/// # use blockstore::InMemoryBlockstore;
/// # use beetswap::BitswapBehaviour;
/// # fn new() -> beetswap::Result<BitswapBehaviour<64, InMemoryBlockstore<64>>> {
/// # fn new() -> beetswap::Result<beetswap::Behaviour<64, InMemoryBlockstore<64>>> {
/// # Ok(
/// BitswapBehaviour::builder(InMemoryBlockstore::new())
/// beetswap::Behaviour::builder(InMemoryBlockstore::new())
/// .protocol_prefix("/celestia/celestia")?
/// .build()
/// # )
/// # }
/// ```
pub fn protocol_prefix(mut self, prefix: &str) -> Result<Self> {
if prefix.starts_with('/') {
return Err(BitswapError::InvalidProtocolPrefix(prefix.to_owned()));
return Err(Error::InvalidProtocolPrefix(prefix.to_owned()));
}

self.protocol_prefix = Some(prefix.to_owned());
Expand All @@ -80,9 +78,8 @@ where
///
/// ```rust,no_run
/// # use blockstore::InMemoryBlockstore;
/// # use beetswap::BitswapBehaviour;
/// # fn new() -> BitswapBehaviour<64, InMemoryBlockstore<64>> {
/// BitswapBehaviour::builder(InMemoryBlockstore::new())
/// # fn new() -> beetswap::Behaviour<64, InMemoryBlockstore<64>> {
/// beetswap::Behaviour::builder(InMemoryBlockstore::new())
/// .client_set_send_dont_have(false)
/// .build()
/// # }
Expand All @@ -93,12 +90,12 @@ where

/// Register an extra [`Multihasher`].
///
/// Every registration adds new hasher to [`BitswapBehaviour`]. Hashers are used to
/// reconstruct the [`Cid`] from the received data. `BitswapBehaviour` will try them
/// Every registration adds new hasher to [`Behaviour`]. Hashers are used to
/// reconstruct the [`Cid`] from the received data. `Behaviour` will try them
/// in the reverse order they were registered until one successfully constructs
/// [`Multihash`].
///
/// By default `BitswapBehaviourBuilder` is pre-loaded with [`StandardMultihasher`].
/// By default `BehaviourBuilder` is pre-loaded with [`StandardMultihasher`].
///
/// [`StandardMultihasher`]: crate::multihasher::StandardMultihasher
/// [`Cid`]: cid::CidGeneric
Expand All @@ -111,15 +108,15 @@ where
self
}

/// Build a [`BitswapBehaviour`].
pub fn build(self) -> BitswapBehaviour<S, B> {
/// Build a [`Behaviour`].
pub fn build(self) -> Behaviour<S, B> {
let blockstore = Arc::new(self.blockstore);
let multihasher = Arc::new(self.multihasher);
let protocol_prefix = self.protocol_prefix.as_deref();

BitswapBehaviour {
Behaviour {
protocol: stream_protocol(protocol_prefix, "/ipfs/bitswap/1.2.0")
.expect("prefix checked by BitswapBehaviourBuilder::protocol_prefix"),
.expect("prefix checked by beetswap::BehaviourBuilder::protocol_prefix"),
client: ClientBehaviour::new(self.client, blockstore, multihasher, protocol_prefix),
}
}
Expand Down
52 changes: 24 additions & 28 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ use crate::proto::message::mod_Message::{BlockPresenceType, Wantlist as ProtoWan
use crate::proto::message::Message;
use crate::utils::{convert_cid, stream_protocol};
use crate::wantlist::{Wantlist, WantlistState};
use crate::{BitswapError, BitswapEvent, Result, ToBehaviourEvent, ToHandlerEvent};
use crate::{Error, Event, Result, ToBehaviourEvent, ToHandlerEvent};

const SEND_FULL_INTERVAL: Duration = Duration::from_secs(30);

/// ID of an ongoing query.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BitswapQueryId(u64);
pub struct QueryId(u64);

#[derive(Debug)]
pub struct ClientConfig {
Expand All @@ -51,7 +51,7 @@ impl Default for ClientConfig {

enum TaskResult<const S: usize> {
Get(
BitswapQueryId,
QueryId,
CidGeneric<S>,
Result<Option<Vec<u8>>, BlockstoreError>,
),
Expand All @@ -66,12 +66,12 @@ where
{
store: Arc<B>,
protocol: StreamProtocol,
queue: VecDeque<ToSwarm<BitswapEvent, ToHandlerEvent>>,
queue: VecDeque<ToSwarm<Event, ToHandlerEvent>>,
wantlist: Wantlist<S>,
peers: FnvHashMap<PeerId, PeerState<S>>,
cid_to_queries: FnvHashMap<CidGeneric<S>, SmallVec<[BitswapQueryId; 1]>>,
cid_to_queries: FnvHashMap<CidGeneric<S>, SmallVec<[QueryId; 1]>>,
tasks: FuturesUnordered<BoxFuture<'static, TaskResult<S>>>,
query_abort_handle: FnvHashMap<BitswapQueryId, AbortHandle>,
query_abort_handle: FnvHashMap<QueryId, AbortHandle>,
next_query_id: u64,
waker: Arc<AtomicWaker>,
multihasher: Arc<MultihasherTable<S>>,
Expand Down Expand Up @@ -105,7 +105,7 @@ where
protocol_prefix: Option<&str>,
) -> Self {
let protocol = stream_protocol(protocol_prefix, "/ipfs/bitswap/1.2.0")
.expect("prefix checked by BitswapBehaviourBuilder::protocol_prefix");
.expect("prefix checked by beetswap::BehaviourBuilder::protocol_prefix");
let set_send_dont_have = config.set_send_dont_have;

ClientBehaviour {
Expand Down Expand Up @@ -154,14 +154,14 @@ where
}
}

fn next_query_id(&mut self) -> BitswapQueryId {
let id = BitswapQueryId(self.next_query_id);
fn next_query_id(&mut self) -> QueryId {
let id = QueryId(self.next_query_id);
self.next_query_id += 1;
id
}

/// Schedule a `Blockstore::get` for the specified cid
fn schedule_store_get(&mut self, query_id: BitswapQueryId, cid: CidGeneric<S>) {
fn schedule_store_get(&mut self, query_id: QueryId, cid: CidGeneric<S>) {
let store = self.store.clone();
let (handle, reg) = AbortHandle::new_pair();

Expand Down Expand Up @@ -193,7 +193,7 @@ where
);
}

pub(crate) fn get<const CS: usize>(&mut self, cid: &CidGeneric<CS>) -> BitswapQueryId {
pub(crate) fn get<const CS: usize>(&mut self, cid: &CidGeneric<CS>) -> QueryId {
let query_id = self.next_query_id();

match convert_cid(cid) {
Expand All @@ -204,17 +204,17 @@ where
// the requestor on the next `poll`.
None => {
self.queue
.push_back(ToSwarm::GenerateEvent(BitswapEvent::GetQueryError {
.push_back(ToSwarm::GenerateEvent(Event::GetQueryError {
query_id,
error: BitswapError::InvalidMultihashSize,
error: Error::InvalidMultihashSize,
}));
}
}

query_id
}

pub(crate) fn cancel(&mut self, query_id: BitswapQueryId) {
pub(crate) fn cancel(&mut self, query_id: QueryId) {
if let Some(abort_handle) = self.query_abort_handle.remove(&query_id) {
abort_handle.abort();
}
Expand Down Expand Up @@ -279,7 +279,7 @@ where
if let Some(queries) = self.cid_to_queries.remove(&cid) {
for query_id in queries {
self.queue
.push_back(ToSwarm::GenerateEvent(BitswapEvent::GetQueryResponse {
.push_back(ToSwarm::GenerateEvent(Event::GetQueryResponse {
query_id,
data: block.data.clone(),
}));
Expand Down Expand Up @@ -347,7 +347,7 @@ where
handler_updated
}

pub(crate) fn poll(&mut self, cx: &mut Context) -> Poll<ToSwarm<BitswapEvent, ToHandlerEvent>> {
pub(crate) fn poll(&mut self, cx: &mut Context) -> Poll<ToSwarm<Event, ToHandlerEvent>> {
// Update waker
self.waker.register(cx.waker());

Expand All @@ -370,12 +370,10 @@ where
match task_result {
// Blockstore already has the data so return them to the user
TaskResult::Get(query_id, _, Ok(Some(data))) => {
return Poll::Ready(ToSwarm::GenerateEvent(
BitswapEvent::GetQueryResponse {
query_id,
data: data.clone(),
},
));
return Poll::Ready(ToSwarm::GenerateEvent(Event::GetQueryResponse {
query_id,
data: data.clone(),
}));
}

// If blockstore doesn't have the data, add CID in the wantlist.
Expand All @@ -388,7 +386,7 @@ where

// Blockstore error
TaskResult::Get(query_id, _, Err(e)) => {
return Poll::Ready(ToSwarm::GenerateEvent(BitswapEvent::GetQueryError {
return Poll::Ready(ToSwarm::GenerateEvent(Event::GetQueryError {
query_id,
error: e.into(),
}));
Expand Down Expand Up @@ -583,7 +581,7 @@ mod tests {
let ev = poll_fn(|cx| client.poll(cx)).await;

match ev {
ToSwarm::GenerateEvent(BitswapEvent::GetQueryResponse { query_id, data }) => {
ToSwarm::GenerateEvent(Event::GetQueryResponse { query_id, data }) => {
if query_id == query_id1 {
assert_eq!(data, b"1");
} else if query_id == query_id2 {
Expand Down Expand Up @@ -782,9 +780,7 @@ mod tests {
let ev = poll_fn(|cx| client.poll(cx)).await;

let (query_id, data) = match ev {
ToSwarm::GenerateEvent(BitswapEvent::GetQueryResponse { query_id, data }) => {
(query_id, data)
}
ToSwarm::GenerateEvent(Event::GetQueryResponse { query_id, data }) => (query_id, data),
_ => unreachable!(),
};

Expand Down Expand Up @@ -929,7 +925,7 @@ mod tests {
}

fn expect_send_wantlist_event(
ev: ToSwarm<BitswapEvent, ToHandlerEvent>,
ev: ToSwarm<Event, ToHandlerEvent>,
) -> (PeerId, ProtoWantlist, Arc<Mutex<SendingState>>) {
match ev {
ToSwarm::NotifyHandler {
Expand Down
Loading

0 comments on commit 64e65d5

Please sign in to comment.