rust_ipfs/unixfs/
get.rs

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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
use std::{
    path::{Path, PathBuf},
    task::Poll,
    time::Duration,
};

use either::Either;
use futures::stream::BoxStream;
use futures::{future::BoxFuture, stream::FusedStream, FutureExt, Stream, StreamExt};
use libp2p::PeerId;
#[allow(unused_imports)]
use rust_unixfs::walk::{ContinuedWalk, Walker};
#[cfg(not(target_arch = "wasm32"))]
use tokio::io::AsyncWriteExt;
use tracing::{Instrument, Span};

use crate::{dag::IpldDag, repo::Repo, Ipfs, IpfsPath};

#[allow(unused_imports)]
use super::{TraversalFailed, UnixfsStatus};

#[must_use = "does nothing unless you `.await` or poll the stream"]
pub struct UnixfsGet {
    core: Option<Either<Ipfs, Repo>>,
    dest: PathBuf,
    span: Span,
    path: Option<IpfsPath>,
    providers: Vec<PeerId>,
    local_only: bool,
    timeout: Option<Duration>,
    stream: Option<BoxStream<'static, UnixfsStatus>>,
}

impl UnixfsGet {
    pub fn with_ipfs(ipfs: &Ipfs, path: impl Into<IpfsPath>, dest: impl AsRef<Path>) -> Self {
        Self::with_either(Either::Left(ipfs.clone()), path, dest)
    }

    pub fn with_repo(repo: &Repo, path: impl Into<IpfsPath>, dest: impl AsRef<Path>) -> Self {
        Self::with_either(Either::Right(repo.clone()), path, dest)
    }

    fn with_either(
        core: Either<Ipfs, Repo>,
        path: impl Into<IpfsPath>,
        dest: impl AsRef<Path>,
    ) -> Self {
        let path = path.into();
        let dest = dest.as_ref().to_path_buf();
        Self {
            core: Some(core),
            dest,
            path: Some(path),
            span: Span::current(),
            providers: Vec::new(),
            local_only: false,
            timeout: None,
            stream: None,
        }
    }

    pub fn span(mut self, span: Span) -> Self {
        self.span = span;
        self
    }

    pub fn provider(mut self, peer_id: PeerId) -> Self {
        if !self.providers.contains(&peer_id) {
            self.providers.push(peer_id);
        }
        self
    }

    pub fn providers(mut self, list: &[PeerId]) -> Self {
        self.providers = list.to_vec();
        self
    }

    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    pub fn local(mut self) -> Self {
        self.local_only = true;
        self
    }

    pub fn set_local(mut self, local: bool) -> Self {
        self.local_only = local;
        self
    }
}

impl Stream for UnixfsGet {
    type Item = UnixfsStatus;
    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        if self.core.is_none() && self.stream.is_none() {
            return Poll::Ready(None);
        }
        loop {
            match &mut self.stream {
                None => {
                    let (repo, dag) = match self.core.take().expect("ipfs or repo is used") {
                        Either::Left(ipfs) => (ipfs.repo().clone(), ipfs.dag()),
                        Either::Right(repo) => (repo.clone(), IpldDag::from(repo.clone())),
                    };

                    let path = self.path.take().expect("starting point exist");
                    let providers = std::mem::take(&mut self.providers);
                    let local_only = self.local_only;
                    let timeout = self.timeout;
                    let dest = self.dest.clone();

                    #[cfg(not(target_arch = "wasm32"))]
                    let stream = async_stream::stream! {

                        let mut cache = None;
                        let mut total_size = None;
                        let mut written = 0;

                        let mut file = match tokio::fs::File::create(dest)
                            .await
                            .map_err(TraversalFailed::Io) {
                                Ok(f) => f,
                                Err(e) => {
                                    yield UnixfsStatus::FailedStatus { written, total_size, error: e.into() };
                                    return;
                                }
                            };

                        let block  = match dag
                            ._resolve(path.clone(), true, &providers, local_only, timeout)
                            .await
                            .map_err(TraversalFailed::Resolving)
                            .and_then(|(resolved, _)| resolved.into_unixfs_block().map_err(TraversalFailed::Path)) {
                                Ok(block) => block,
                                Err(e) => {
                                    yield UnixfsStatus::FailedStatus { written, total_size, error: e.into() };
                                    return;
                                }
                        };

                        let cid = block.cid();
                        let root_name = block.cid().to_string();

                        let mut walker = Walker::new(*cid, root_name);

                        while walker.should_continue() {
                            let (next, _) = walker.pending_links();
                            let block = match repo.get_block(next).providers(&providers).set_local(local_only).timeout(timeout).await {
                                Ok(block) => block,
                                Err(e) => {
                                    yield UnixfsStatus::FailedStatus { written, total_size, error: e };
                                    return;
                                }
                            };
                            let block_data = block.data();

                            match walker.next(block_data, &mut cache) {
                                Ok(ContinuedWalk::Bucket(..)) => {}
                                Ok(ContinuedWalk::File(segment, _, _, _, size)) => {

                                    if segment.is_first() {
                                        total_size = Some(size as usize);
                                        yield UnixfsStatus::ProgressStatus { written, total_size };
                                    }
                                    // even if the largest of files can have 256 kB blocks and about the same
                                    // amount of content, try to consume it in small parts not to grow the buffers
                                    // too much.

                                    let mut n = 0usize;
                                    let slice = segment.as_ref();
                                    let total = slice.len();

                                    while n < total {
                                        let next = &slice[n..];
                                        n += next.len();
                                        if let Err(e) = file.write_all(next).await {
                                            yield UnixfsStatus::FailedStatus { written, total_size, error: e.into() };
                                            return;
                                        }
                                        if let Err(e) = file.sync_all().await {
                                            yield UnixfsStatus::FailedStatus { written, total_size, error: e.into() };
                                            return;
                                        }

                                        written += n;
                                    }

                                    yield UnixfsStatus::ProgressStatus { written, total_size };

                                },
                                Ok(ContinuedWalk::Directory( .. )) | Ok(ContinuedWalk::RootDirectory( .. )) => {}, //TODO
                                Ok(ContinuedWalk::Symlink( .. )) => {},
                                Err(e) => {
                                    yield UnixfsStatus::FailedStatus { written, total_size, error: e.into() };
                                    return;
                                }
                            };
                        };

                        yield UnixfsStatus::CompletedStatus { path, written, total_size }
                    };

                    #[cfg(target_arch = "wasm32")]
                    let stream = async_stream::stream! {
                        _ = repo;
                        _ = dag;
                        _ = path;
                        _ = providers;
                        _ = local_only;
                        _ = timeout;
                        _ = dest;
                        yield UnixfsStatus::FailedStatus { written: 0, total_size: None, error: anyhow::anyhow!("unimplemented") };
                    };

                    self.stream = Some(stream.boxed());
                }
                Some(stream) => match futures::ready!(stream.poll_next_unpin(cx)) {
                    Some(item) => {
                        if matches!(
                            item,
                            UnixfsStatus::FailedStatus { .. }
                                | UnixfsStatus::CompletedStatus { .. }
                        ) {
                            self.stream.take();
                        }
                        return Poll::Ready(Some(item));
                    }
                    None => {
                        self.stream.take();
                        return Poll::Ready(None);
                    }
                },
            }
        }
    }
}

impl std::future::IntoFuture for UnixfsGet {
    type Output = Result<(), anyhow::Error>;

    type IntoFuture = BoxFuture<'static, Self::Output>;

    fn into_future(mut self) -> Self::IntoFuture {
        let span = self.span.clone();
        async move {
            while let Some(status) = self.next().await {
                match status {
                    UnixfsStatus::FailedStatus { error, .. } => {
                        return Err(error);
                    }
                    UnixfsStatus::CompletedStatus { .. } => return Ok(()),
                    _ => {}
                }
            }
            Err::<_, anyhow::Error>(anyhow::anyhow!("Unable to get file"))
        }
        .instrument(span)
        .boxed()
    }
}

impl FusedStream for UnixfsGet {
    fn is_terminated(&self) -> bool {
        self.stream.is_none() && self.core.is_none()
    }
}