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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
use std::{
    path::{Path, PathBuf},
    task::Poll,
};

use crate::{repo::Repo, Block};
use bytes::Bytes;
use either::Either;
#[allow(unused_imports)]
use futures::{
    future::BoxFuture,
    stream::{BoxStream, FusedStream},
    FutureExt, Stream, StreamExt, TryFutureExt,
};
use rust_unixfs::file::adder::{Chunker, FileAdderBuilder};
#[cfg(not(target_arch = "wasm32"))]
use tokio_util::io::ReaderStream;
use tracing::{Instrument, Span};

use crate::{Ipfs, IpfsPath};

use super::{StatusStreamState, UnixfsStatus};

pub enum AddOpt {
    File(PathBuf),
    Stream {
        name: Option<String>,
        total: Option<usize>,
        stream: BoxStream<'static, std::result::Result<Bytes, std::io::Error>>,
    },
}

impl From<PathBuf> for AddOpt {
    fn from(path: PathBuf) -> Self {
        AddOpt::File(path)
    }
}

impl From<&Path> for AddOpt {
    fn from(path: &Path) -> Self {
        AddOpt::File(path.to_path_buf())
    }
}

#[must_use = "do nothing unless you `.await` or poll the stream"]
pub struct UnixfsAdd {
    core: Option<Either<Ipfs, Repo>>,
    opt: Option<AddOpt>,
    span: Span,
    chunk: Chunker,
    pin: bool,
    provide: bool,
    wrap: bool,
    stream: StatusStreamState,
}

impl UnixfsAdd {
    pub fn with_ipfs(ipfs: &Ipfs, opt: impl Into<AddOpt>) -> Self {
        Self::with_either(Either::Left(ipfs.clone()), opt)
    }

    pub fn with_repo(repo: &Repo, opt: impl Into<AddOpt>) -> Self {
        Self::with_either(Either::Right(repo.clone()), opt)
    }

    fn with_either(core: Either<Ipfs, Repo>, opt: impl Into<AddOpt>) -> Self {
        let opt = opt.into();
        Self {
            core: Some(core),
            opt: Some(opt),
            span: Span::current(),
            chunk: Chunker::Size(256 * 1024),
            pin: true,
            provide: false,
            wrap: false,
            stream: StatusStreamState::None,
        }
    }

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

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

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

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

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

impl Stream for UnixfsAdd {
    type Item = UnixfsStatus;
    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        loop {
            match &mut self.stream {
                StatusStreamState::None => {
                    let (ipfs, repo) = match self.core.take().expect("ipfs or repo is used") {
                        Either::Left(ipfs) => {
                            let repo = ipfs.repo().clone();
                            (Some(ipfs), repo)
                        }
                        Either::Right(repo) => (None, repo),
                    };
                    let option = self.opt.take().expect("option already constructed");
                    let chunk = self.chunk;
                    let pin = self.pin;
                    let provide = self.provide;
                    let wrap = self.wrap;

                    let stream = async_stream::stream! {
                        let _g = repo.gc_guard().await;

                        let mut written = 0;

                        let (name, total_size, mut stream) = match option {
                            #[cfg(not(target_arch = "wasm32"))]
                            AddOpt::File(path) => match tokio::fs::File::open(path.clone())
                                .and_then(|file| async move {
                                    let size = file.metadata().await?.len() as usize;

                                    let stream = ReaderStream::new(file);

                                    let name: Option<String> = path.file_name().map(|f| f.to_string_lossy().to_string());

                                    Ok((name, Some(size), stream.boxed()))
                                }).await {
                                    Ok(s) => s,
                                    Err(e) => {
                                        yield UnixfsStatus::FailedStatus { written, total_size: None, error: Some(anyhow::Error::from(e)) };
                                        return;
                                    }
                                },
                            #[cfg(target_arch = "wasm32")]
                            AddOpt::File(_) => {
                                yield UnixfsStatus::FailedStatus { written, total_size: None, error: Some(anyhow::anyhow!("unimplemented")) };
                                return;
                            },
                            AddOpt::Stream { name, total, stream } => (name, total, stream),
                        };

                        let mut adder = FileAdderBuilder::default()
                            .with_chunker(chunk)
                            .build();

                        yield UnixfsStatus::ProgressStatus { written, total_size };

                        while let Some(buffer) = stream.next().await {
                            let buffer = match buffer {
                                Ok(buf) => buf,
                                Err(e) => {
                                    yield UnixfsStatus::FailedStatus { written, total_size, error: Some(anyhow::Error::from(e)) };
                                    return;
                                }
                            };

                            let mut total = 0;
                            while total < buffer.len() {
                                let (blocks, consumed) = adder.push(&buffer[total..]);
                                for (cid, block) in blocks {
                                    let block = match Block::new(cid, block) {
                                        Ok(block) => block,
                                        Err(e) => {
                                            yield UnixfsStatus::FailedStatus { written, total_size, error: Some(e) };
                                            return;
                                        }
                                    };
                                    let _cid = match repo.put_block(block).await {
                                        Ok(cid) => cid,
                                        Err(e) => {
                                            yield UnixfsStatus::FailedStatus { written, total_size, error: Some(e) };
                                            return;
                                        }
                                    };
                                }
                                total += consumed;
                                written += consumed;
                            }

                            yield UnixfsStatus::ProgressStatus { written, total_size };
                        }

                        let blocks = adder.finish();
                        let mut last_cid = None;

                        for (cid, block) in blocks {
                            let block = match Block::new(cid, block) {
                                Ok(block) => block,
                                Err(e) => {
                                    yield UnixfsStatus::FailedStatus { written, total_size, error: Some(e) };
                                    return;
                                }
                            };
                            let _cid = match repo.put_block(block).await {
                                Ok(cid) => cid,
                                Err(e) => {
                                    yield UnixfsStatus::FailedStatus { written, total_size, error: Some(e) };
                                    return;
                                }
                            };
                            last_cid = Some(cid);
                        }

                        let cid = match last_cid {
                            Some(cid) => cid,
                            None => {
                                yield UnixfsStatus::FailedStatus { written, total_size, error: None };
                                return;
                            }
                        };

                        let mut path = IpfsPath::from(cid);

                        if wrap {
                            if let Some(name) = name {
                                let result = {
                                    let repo = repo.clone();
                                    async move {
                                        let mut opts = rust_unixfs::dir::builder::TreeOptions::default();
                                        opts.wrap_with_directory();

                                        let mut tree = rust_unixfs::dir::builder::BufferingTreeBuilder::new(opts);
                                        tree.put_link(&name, cid, written as _)?;

                                        let mut iter = tree.build();
                                        let mut cids = Vec::new();

                                        while let Some(node) = iter.next_borrowed() {
                                            let node = node?;
                                            let block = Block::new(node.cid.to_owned(), node.block.into())?;

                                            repo.put_block(block).await?;

                                            cids.push(*node.cid);
                                        }
                                        let cid = cids.last().ok_or(anyhow::anyhow!("no cid available"))?;
                                        let path = IpfsPath::from(*cid).sub_path(&name)?;

                                        Ok::<_, anyhow::Error>(path)
                                    }
                                };

                                path = match result.await {
                                    Ok(path) => path,
                                    Err(e) => {
                                        yield UnixfsStatus::FailedStatus { written, total_size, error: Some(e) };
                                        return;
                                    }
                                };
                            }
                        }

                        let cid = path.root().cid().copied().expect("Cid is apart of the path");

                        if pin {
                            if let Ok(false) = repo.is_pinned(&cid).await {
                                if let Err(e) = repo.pin(&cid).recursive().await {
                                    error!("Unable to pin {cid}: {e}");
                                }
                            }
                        }

                        if provide {
                            if let Some(ipfs) = ipfs {
                                if let Err(e) = ipfs.provide(cid).await {
                                    error!("Unable to provide {cid}: {e}");
                                }
                            }
                        }


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

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

impl std::future::IntoFuture for UnixfsAdd {
    type Output = Result<IpfsPath, 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::CompletedStatus { path, .. } => return Ok(path),
                    UnixfsStatus::FailedStatus { error, .. } => {
                        return Err(error.unwrap_or(anyhow::anyhow!("Unable to add file")));
                    }
                    _ => {}
                }
            }
            Err::<_, anyhow::Error>(anyhow::anyhow!("Unable to add file"))
        }
        .instrument(span)
        .boxed()
    }
}

impl FusedStream for UnixfsAdd {
    fn is_terminated(&self) -> bool {
        matches!(self.stream, StatusStreamState::Done) && self.core.is_none()
    }
}