1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
use crate::IpfsClient;
use anyhow::Result;
use async_trait::async_trait;
use cid::Cid;
use noosphere_storage::{BlockStore, Storage};
use std::sync::Arc;
use tokio::sync::RwLock;

#[cfg(doc)]
use noosphere_storage::KeyValueStore;

/// [IpfsStorage] is an implementation of [Storage] that wraps another
/// implementation of [Storage] and an [IpfsClient].
/// [IpfsStorage] is generic over [BlockStore] and [KeyValueStore]
/// but will produce a [IpfsStore] wrapped [BlockStore]
#[derive(Clone)]
pub struct IpfsStorage<S, C>
where
    S: Storage,
    C: IpfsClient,
{
    local_storage: S,
    ipfs_client: Option<C>,
}

impl<S, C> IpfsStorage<S, C>
where
    S: Storage,
    C: IpfsClient,
{
    pub fn new(local_storage: S, ipfs_client: Option<C>) -> Self {
        IpfsStorage {
            local_storage,
            ipfs_client,
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub trait IpfsStorageConditionalSendSync: Send + Sync {}

#[cfg(not(target_arch = "wasm32"))]
impl<S> IpfsStorageConditionalSendSync for S where S: Send + Sync {}

#[cfg(target_arch = "wasm32")]
pub trait IpfsStorageConditionalSendSync {}

#[cfg(target_arch = "wasm32")]
impl<S> IpfsStorageConditionalSendSync for S {}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl<S, C> Storage for IpfsStorage<S, C>
where
    S: Storage + IpfsStorageConditionalSendSync,
    C: IpfsClient + IpfsStorageConditionalSendSync,
{
    type BlockStore = IpfsStore<S::BlockStore, C>;

    type KeyValueStore = S::KeyValueStore;

    async fn get_block_store(&self, name: &str) -> Result<Self::BlockStore> {
        let store = self.local_storage.get_block_store(name).await?;
        Ok(IpfsStore::new(store, self.ipfs_client.clone()))
    }

    async fn get_key_value_store(&self, name: &str) -> Result<Self::KeyValueStore> {
        self.local_storage.get_key_value_store(name).await
    }
}

/// An implementation of [BlockStore] that wraps some other implementation of
/// same. It forwards most behavior to its wrapped implementation, except when
/// reading blocks. In that case, if a block cannot be found locally, it will
/// attempt to fail-over by requesting the block from a configured IPFS gateway
/// API. If the block is found, it is added to local storage and then returned
/// as normal
#[derive(Clone)]
pub struct IpfsStore<B, C>
where
    B: BlockStore,
    C: IpfsClient + IpfsStorageConditionalSendSync,
{
    local_store: Arc<RwLock<B>>,
    ipfs_client: Option<C>,
}

impl<B, C> IpfsStore<B, C>
where
    B: BlockStore,
    C: IpfsClient + IpfsStorageConditionalSendSync,
{
    pub fn new(block_store: B, ipfs_client: Option<C>) -> Self {
        IpfsStore {
            local_store: Arc::new(RwLock::new(block_store)),
            ipfs_client,
        }
    }
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl<B, C> BlockStore for IpfsStore<B, C>
where
    B: BlockStore,
    C: IpfsClient + IpfsStorageConditionalSendSync,
{
    async fn put_block(&mut self, cid: &Cid, block: &[u8]) -> Result<()> {
        let mut local_store = self.local_store.write().await;
        local_store.put_block(cid, block).await
    }

    async fn get_block(&self, cid: &Cid) -> Result<Option<Vec<u8>>> {
        let maybe_block = {
            let local_store = self.local_store.read().await;
            local_store.get_block(cid).await?
        };

        if let Some(block) = maybe_block {
            return Ok(Some(block));
        }

        if let Some(ipfs_client) = self.ipfs_client.as_ref() {
            if let Some(bytes) = ipfs_client.get_block(cid).await? {
                let mut local_store = self.local_store.write().await;
                local_store.put_block(cid, &bytes).await?;
                return Ok(Some(bytes));
            }
        }
        Ok(None)
    }
}