Skip to content

Commit 48822a1

Browse files
authored
feat: Use RepoType in Repo and impl DefaultStorage (#414)
1 parent 4d3ce5c commit 48822a1

29 files changed

+882
-295
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
- chore: use async-rt in place of rt utils. [PR 362](https://github.com/dariusc93/rust-ipfs/pull/362)
88
- feat: Implement configuration for connecting to IPFS Private Network. [PR 398](https://github.com/dariusc93/rust-ipfs/pull/398)
99
- refactor: use CommunicationTask to handle sending message to IpfsTask. [PR 404](https://github.com/dariusc93/rust-ipfs/pull/404)
10+
- feat: Use RepoType in Repo and impl DefaultStorage. [PR 414](https://github.com/dariusc93/rust-ipfs/pull/414)
1011

1112
# 0.14.1
1213
- fix: remove expect when session failed to get next block.

src/dag.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
use crate::block::BlockCodec;
44
use crate::error::Error;
55
use crate::path::{IpfsPath, PathRoot, SlashedPath};
6+
use crate::repo::default_impl::DefaultStorage;
67
use crate::repo::Repo;
78
use crate::{Block, Ipfs};
89
use bytes::Bytes;
@@ -179,11 +180,11 @@ impl RawResolveLocalError {
179180
#[derive(Clone, Debug)]
180181
pub struct IpldDag {
181182
ipfs: Option<Ipfs>,
182-
repo: Repo,
183+
repo: Repo<DefaultStorage>,
183184
}
184185

185-
impl From<Repo> for IpldDag {
186-
fn from(repo: Repo) -> Self {
186+
impl From<Repo<DefaultStorage>> for IpldDag {
187+
fn from(repo: Repo<DefaultStorage>) -> Self {
187188
IpldDag { ipfs: None, repo }
188189
}
189190
}

src/ipns/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use std::borrow::Borrow;
55

66
use crate::p2p::DnsResolver;
77
use crate::path::{IpfsPath, PathRoot};
8+
use crate::repo::DataStore;
89
use crate::Ipfs;
910

1011
mod dnslink;

src/lib.rs

Lines changed: 57 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ use p2p::{
6161
RelayConfig, RequestResponseConfig, SwarmConfig, TransportConfig,
6262
};
6363
use repo::{
64-
BlockStore, DataStore, GCConfig, GCTrigger, Lock, RepoFetch, RepoInsertPin, RepoRemovePin,
64+
default_impl::DefaultStorage, GCConfig, GCTrigger, RepoFetch, RepoInsertPin, RepoRemovePin,
6565
};
6666

6767
use tracing::Span;
@@ -87,8 +87,8 @@ pub use self::{
8787
use async_rt::{AbortableJoinHandle, CommunicationTask};
8888
use ipld_core::cid::Cid;
8989
use ipld_core::ipld::Ipld;
90-
use std::borrow::Borrow;
9190
use std::convert::Infallible;
91+
use std::{borrow::Borrow, path::PathBuf};
9292
use std::{
9393
collections::{BTreeSet, HashMap, HashSet},
9494
fmt,
@@ -126,51 +126,6 @@ use libp2p::{request_response::InboundRequestId, swarm::dial_opts::PeerCondition
126126
pub use libp2p_connection_limits::ConnectionLimits;
127127
use serde::Serialize;
128128

129-
#[allow(dead_code)]
130-
#[deprecated(note = "Use `StoreageType` instead")]
131-
type StoragePath = StorageType;
132-
133-
#[derive(Default, Debug)]
134-
pub enum StorageType {
135-
#[cfg(not(target_arch = "wasm32"))]
136-
Disk(std::path::PathBuf),
137-
#[default]
138-
Memory,
139-
#[cfg(target_arch = "wasm32")]
140-
IndexedDb { namespace: Option<String> },
141-
Custom {
142-
blockstore: Option<Box<dyn BlockStore>>,
143-
datastore: Option<Box<dyn DataStore>>,
144-
lock: Option<Box<dyn Lock>>,
145-
},
146-
}
147-
148-
impl PartialEq for StorageType {
149-
fn eq(&self, other: &Self) -> bool {
150-
match (self, other) {
151-
#[cfg(not(target_arch = "wasm32"))]
152-
(StorageType::Disk(left_path), StorageType::Disk(right_path)) => {
153-
left_path.eq(right_path)
154-
}
155-
#[cfg(target_arch = "wasm32")]
156-
(
157-
StorageType::IndexedDb { namespace: left },
158-
StorageType::IndexedDb { namespace: right },
159-
) => left.eq(right),
160-
(StorageType::Memory, StorageType::Memory) => true,
161-
(StorageType::Custom { .. }, StorageType::Custom { .. }) => {
162-
//Do we really care if they equal?
163-
//TODO: Possibly implement PartialEq/Eq for the traits so we could make sure
164-
// that they do or dont eq each other. For now this will always be true
165-
true
166-
}
167-
_ => false,
168-
}
169-
}
170-
}
171-
172-
impl Eq for StorageType {}
173-
174129
/// Ipfs node options used to configure the node to be created with [`UninitializedIpfs`].
175130
struct IpfsOptions {
176131
/// The path of the ipfs repo (blockstore and datastore).
@@ -182,7 +137,11 @@ struct IpfsOptions {
182137
///
183138
/// It is **not** recommended to set this to IPFS_PATH without first at least backing up your
184139
/// existing repository.
185-
pub ipfs_path: StorageType,
140+
pub ipfs_path: Option<PathBuf>,
141+
142+
/// Enables and supply a name of the namespace used for indexeddb
143+
#[cfg(target_arch = "wasm32")]
144+
pub namespace: Option<Option<String>>,
186145

187146
/// Nodes used as bootstrap peers.
188147
pub bootstrap: Vec<Multiaddr>,
@@ -285,7 +244,9 @@ pub enum RepoProvider {
285244
impl Default for IpfsOptions {
286245
fn default() -> Self {
287246
Self {
288-
ipfs_path: StorageType::Memory,
247+
ipfs_path: None,
248+
#[cfg(target_arch = "wasm32")]
249+
namespace: None,
289250
bootstrap: Default::default(),
290251
relay_server_config: Default::default(),
291252
kad_configuration: Either::Left(Default::default()),
@@ -333,7 +294,7 @@ impl fmt::Debug for IpfsOptions {
333294
#[allow(clippy::type_complexity)]
334295
pub struct Ipfs {
335296
span: Span,
336-
repo: Repo,
297+
repo: Repo<DefaultStorage>,
337298
key: Keypair,
338299
keystore: Keystore,
339300
identify_conf: IdentifyConfiguration,
@@ -557,7 +518,7 @@ pub struct UninitializedIpfs<C: NetworkBehaviour<ToSwarm = Infallible> + Send> {
557518
keys: Option<Keypair>,
558519
options: IpfsOptions,
559520
fdlimit: Option<FDLimit>,
560-
repo_handle: Option<Repo>,
521+
repo_handle: Repo<DefaultStorage>,
561522
local_external_addr: bool,
562523
swarm_event: Option<TSwarmEventFn<C>>,
563524
// record_validators: HashMap<String, Arc<dyn Fn(&str, &Record) -> bool + Sync + Send>>,
@@ -583,7 +544,7 @@ impl<C: NetworkBehaviour<ToSwarm = Infallible> + Send> UninitializedIpfs<C> {
583544
keys: None,
584545
options: Default::default(),
585546
fdlimit: None,
586-
repo_handle: None,
547+
repo_handle: Repo::new_memory(),
587548
// record_validators: Default::default(),
588549
record_key_validator: Default::default(),
589550
local_external_addr: false,
@@ -604,10 +565,10 @@ impl<C: NetworkBehaviour<ToSwarm = Infallible> + Send> UninitializedIpfs<C> {
604565
}
605566

606567
/// Set storage type for the repo.
607-
pub fn set_storage_type(mut self, storage_type: StorageType) -> Self {
608-
self.options.ipfs_path = storage_type;
609-
self
610-
}
568+
// pub fn set_storage_type(mut self, storage_type: StorageType) -> Self {
569+
// self.options.ipfs_path = storage_type;
570+
// self
571+
// }
611572

612573
/// Adds a listening address
613574
pub fn add_listening_addr(mut self, addr: Multiaddr) -> Self {
@@ -792,7 +753,14 @@ impl<C: NetworkBehaviour<ToSwarm = Infallible> + Send> UninitializedIpfs<C> {
792753
#[cfg(not(target_arch = "wasm32"))]
793754
pub fn set_path<P: AsRef<Path>>(mut self, path: P) -> Self {
794755
let path = path.as_ref().to_path_buf();
795-
self.options.ipfs_path = StorageType::Disk(path);
756+
self.options.ipfs_path = Some(path);
757+
self
758+
}
759+
760+
/// Sets a namespace
761+
#[cfg(target_arch = "wasm32")]
762+
pub fn set_namespace(mut self, ns: Option<String>) -> Self {
763+
self.options.namespace = Some(ns);
796764
self
797765
}
798766

@@ -853,8 +821,8 @@ impl<C: NetworkBehaviour<ToSwarm = Infallible> + Send> UninitializedIpfs<C> {
853821
}
854822

855823
/// Set block and data repo
856-
pub fn set_repo(mut self, repo: &Repo) -> Self {
857-
self.repo_handle = Some(repo.clone());
824+
pub fn set_repo(mut self, repo: &Repo<DefaultStorage>) -> Self {
825+
self.repo_handle = Repo::clone(repo);
858826
self
859827
}
860828

@@ -940,23 +908,32 @@ impl<C: NetworkBehaviour<ToSwarm = Infallible> + Send> UninitializedIpfs<C> {
940908
// instruments the IpfsFuture, the background task.
941909
let swarm_span = tracing::trace_span!(parent: &root_span, "swarm");
942910

943-
let repo = match repo_handle {
944-
Some(repo) => {
945-
if repo.is_online() {
946-
anyhow::bail!("Repo is already initialized");
947-
}
948-
repo
949-
}
950-
None => {
951-
#[cfg(not(target_arch = "wasm32"))]
952-
if let StorageType::Disk(path) = &options.ipfs_path {
911+
let mut repo = repo_handle;
912+
913+
if repo.is_online() {
914+
anyhow::bail!("Repo is already initialized");
915+
}
916+
917+
#[cfg(not(target_arch = "wasm32"))]
918+
{
919+
repo = match &options.ipfs_path {
920+
Some(path) => {
953921
if !path.is_dir() {
954922
tokio::fs::create_dir_all(path).await?;
955923
}
924+
Repo::<DefaultStorage>::new_fs(path)
956925
}
957-
Repo::new(&mut options.ipfs_path)
958-
}
959-
};
926+
None => repo,
927+
};
928+
}
929+
930+
#[cfg(target_arch = "wasm32")]
931+
{
932+
repo = match options.namespace.take() {
933+
Some(ns) => Repo::<DefaultStorage>::new_idb(ns),
934+
None => repo,
935+
};
936+
}
960937

961938
repo.init().instrument(init_span.clone()).await?;
962939

@@ -1039,7 +1016,7 @@ impl<C: NetworkBehaviour<ToSwarm = Infallible> + Send> UninitializedIpfs<C> {
10391016

10401017
let gc_handle = gc_config.map(|config| {
10411018
async_rt::task::spawn_abortable({
1042-
let repo = repo.clone();
1019+
let repo = Repo::clone(&repo);
10431020
async move {
10441021
let GCConfig { duration, trigger } = config;
10451022
let use_config_timer = duration != Duration::ZERO;
@@ -1176,7 +1153,7 @@ impl Ipfs {
11761153
}
11771154

11781155
/// Return an [`Repo`] to access the internal repo of the node
1179-
pub fn repo(&self) -> &Repo {
1156+
pub fn repo(&self) -> &Repo<DefaultStorage> {
11801157
&self.repo
11811158
}
11821159

@@ -1191,13 +1168,13 @@ impl Ipfs {
11911168
}
11921169

11931170
/// Puts a block into the ipfs repo.
1194-
pub fn put_block(&self, block: &Block) -> RepoPutBlock {
1171+
pub fn put_block(&self, block: &Block) -> RepoPutBlock<DefaultStorage> {
11951172
self.repo.put_block(block).span(self.span.clone())
11961173
}
11971174

11981175
/// Retrieves a block from the local blockstore, or starts fetching from the network or join an
11991176
/// already started fetch.
1200-
pub fn get_block(&self, cid: impl Borrow<Cid>) -> RepoGetBlock {
1177+
pub fn get_block(&self, cid: impl Borrow<Cid>) -> RepoGetBlock<DefaultStorage> {
12011178
self.repo.get_block(cid).span(self.span.clone())
12021179
}
12031180

@@ -1239,7 +1216,7 @@ impl Ipfs {
12391216
/// If a recursive `insert_pin` operation is interrupted because of a crash or the crash
12401217
/// prevents from synchronizing the data store to disk, this will leave the system in an inconsistent
12411218
/// state. The remedy is to re-pin recursive pins.
1242-
pub fn insert_pin(&self, cid: impl Borrow<Cid>) -> RepoInsertPin {
1219+
pub fn insert_pin(&self, cid: impl Borrow<Cid>) -> RepoInsertPin<DefaultStorage> {
12431220
self.repo().pin(cid).span(self.span.clone())
12441221
}
12451222

@@ -1249,7 +1226,7 @@ impl Ipfs {
12491226
///
12501227
/// Unpinning an indirectly pinned Cid is not possible other than through its recursively
12511228
/// pinned tree roots.
1252-
pub fn remove_pin(&self, cid: impl Borrow<Cid>) -> RepoRemovePin {
1229+
pub fn remove_pin(&self, cid: impl Borrow<Cid>) -> RepoRemovePin<DefaultStorage> {
12531230
self.repo().remove_pin(cid).span(self.span.clone())
12541231
}
12551232

@@ -2131,7 +2108,7 @@ impl Ipfs {
21312108
}
21322109

21332110
/// Fetches the block, and, if set, recursively walk the graph loading all the blocks to the blockstore.
2134-
pub fn fetch(&self, cid: &Cid) -> RepoFetch {
2111+
pub fn fetch(&self, cid: &Cid) -> RepoFetch<DefaultStorage> {
21352112
self.repo.fetch(cid).span(self.span.clone())
21362113
}
21372114

@@ -3085,6 +3062,7 @@ pub use node::Node;
30853062

30863063
/// Node module provides an easy to use interface used in `tests/`.
30873064
mod node {
3065+
30883066
use super::*;
30893067

30903068
/// Node encapsulates everything to setup a testing instance so that multi-node tests become

src/p2p/behaviour.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use either::Either;
99
use serde::{Deserialize, Serialize};
1010

1111
use crate::error::Error;
12+
use crate::repo::default_impl::DefaultStorage;
1213
use crate::{IntoAddPeerOpt, IpfsOptions};
1314

1415
use crate::repo::Repo;
@@ -362,7 +363,7 @@ where
362363
pub(crate) fn new(
363364
keypair: &Keypair,
364365
options: &IpfsOptions,
365-
repo: &Repo,
366+
repo: &Repo<DefaultStorage>,
366367
custom: Option<C>,
367368
) -> Result<(Self, Option<ClientTransport>), Error> {
368369
let bootstrap = options.bootstrap.clone();

src/p2p/bitswap.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,10 @@ mod bitswap_pb {
3535
}
3636
}
3737

38-
use crate::{repo::Repo, Block};
38+
use crate::{
39+
repo::{default_impl::DefaultStorage, Repo},
40+
Block,
41+
};
3942

4043
use self::{
4144
message::{BitswapMessage, BitswapRequest, BitswapResponse, RequestType},
@@ -62,14 +65,14 @@ pub struct Behaviour {
6265
events: VecDeque<ToSwarm<<Self as NetworkBehaviour>::ToSwarm, THandlerInEvent<Self>>>,
6366
connections: HashMap<PeerId, HashSet<ConnectionId>>,
6467
blacklist_connections: HashMap<PeerId, BTreeSet<ConnectionId>>,
65-
store: Repo,
68+
store: Repo<DefaultStorage>,
6669
want_session: StreamMap<Cid, WantSession>,
6770
have_session: StreamMap<Cid, HaveSession>,
6871
waker: Option<Waker>,
6972
}
7073

7174
impl Behaviour {
72-
pub fn new(store: &Repo) -> Self {
75+
pub fn new(store: &Repo<DefaultStorage>) -> Self {
7376
Self {
7477
events: Default::default(),
7578
connections: Default::default(),
@@ -559,7 +562,7 @@ impl NetworkBehaviour for Behaviour {
559562
mod test {
560563
use std::time::Duration;
561564

562-
use crate::block::BlockCodec;
565+
use crate::{block::BlockCodec, repo::default_impl::DefaultStorage};
563566
use futures::StreamExt;
564567
use ipld_core::cid::Cid;
565568
use libp2p::{
@@ -954,7 +957,7 @@ mod test {
954957
Ok(())
955958
}
956959

957-
async fn build_swarm() -> (PeerId, Multiaddr, Swarm<Behaviour>, Repo) {
960+
async fn build_swarm() -> (PeerId, Multiaddr, Swarm<Behaviour>, Repo<DefaultStorage>) {
958961
let repo = Repo::new_memory();
959962

960963
let mut swarm = SwarmBuilder::with_new_identity()

0 commit comments

Comments
 (0)