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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
use std::{
    collections::HashMap,
    task::{Context, Poll},
};

use bytes::Bytes;
use futures::{ready, Stream, StreamExt};
use pin_project_lite::pin_project;

use crate::errors::CondowError;

use super::{BytesHint, ChunkStream, ChunkStreamItem};

/// The type of the elements returned by a [PartStream]
pub type PartStreamItem = Result<Part, CondowError>;

/// A downloaded part consisting of 1 or more chunks
#[derive(Debug, Clone)]
pub struct Part {
    /// Index of the part this chunk belongs to
    pub part_index: usize,
    /// Offset of the first chunk within the BLOB
    pub blob_offset: usize,
    /// Offset of the first chunk within the downloaded range
    pub range_offset: usize,
    /// The chunks of bytes in the order received for this part
    pub chunks: Vec<Bytes>,
}

impl Part {
    /// Length of this [Part] in bytes
    pub fn len(&self) -> usize {
        self.chunks.iter().map(|b| b.len()).sum()
    }

    /// Returns `true` if there are no bytes in this [Part]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// A struct to collect and aggregate received chunks for a part
struct PartEntry {
    part_index: usize,
    blob_offset: usize,
    range_offset: usize,
    chunks: Vec<Bytes>,
    is_complete: bool,
}

pin_project! {
    /// A stream of downloaded parts
    ///
    /// All parts and their chunks are ordered as they would
    /// have appeared in a sequential download of a range/BLOB
    pub struct PartStream<St> {
        bytes_hint: BytesHint,
        #[pin]
        stream: St,
        is_closed: bool,
        next_part_idx: usize,
        collected_parts: HashMap<usize, PartEntry>
    }
}

impl<St: Stream<Item = ChunkStreamItem> + Unpin> PartStream<St> {
    /// Create a new [PartStream].
    ///
    /// **Call with care.** This function will only work
    /// if the input stream was not iterated before
    /// since all chunks are needed. The stream might live lock
    /// if the input was already iterated.
    pub fn new(stream: St, bytes_hint: BytesHint) -> Self {
        Self {
            bytes_hint,
            stream,
            is_closed: false,
            next_part_idx: 0,
            collected_parts: HashMap::default(),
        }
    }

    /// Hint on the remaining bytes on this stream.
    pub fn bytes_hint(&self) -> BytesHint {
        self.bytes_hint
    }

    /// Writes all bytes left on the stream into the provided buffer
    ///
    /// Fails if the buffer is too small or there was an error on the stream.
    pub async fn write_buffer(mut self, buffer: &mut [u8]) -> Result<usize, CondowError> {
        if buffer.len() < self.bytes_hint.lower_bound() {
            return Err(CondowError::new_other(format!(
                "buffer to small ({}). at least {} bytes required",
                buffer.len(),
                self.bytes_hint.lower_bound()
            )));
        }

        let mut offset = 0;
        while let Some(next) = self.next().await {
            let part = next?;

            for chunk in part.chunks {
                let end_excl = offset + chunk.len();
                if end_excl > buffer.len() {
                    return Err(CondowError::new_other(format!(
                        "write attempt beyond buffer end (buffer len = {}). \
                        attempted to write at index {}",
                        buffer.len(),
                        end_excl
                    )));
                }

                buffer[offset..end_excl].copy_from_slice(&chunk[..]);

                offset = end_excl;
            }
        }

        Ok(offset)
    }

    /// Creates a `Vec<u8>` filled with the rest of the bytes from the stream.
    ///
    /// Fails if there is an error on the stream
    pub async fn into_vec(mut self) -> Result<Vec<u8>, CondowError> {
        if let Some(total_bytes) = self.bytes_hint.exact() {
            let mut buffer = vec![0; total_bytes];
            let _ = self.write_buffer(buffer.as_mut()).await?;
            Ok(buffer)
        } else {
            let mut buffer = Vec::with_capacity(self.bytes_hint.lower_bound());

            while let Some(next) = self.next().await {
                let part = next?;

                for chunk in part.chunks {
                    buffer.extend(chunk);
                }
            }

            Ok(buffer)
        }
    }
}

impl PartStream<ChunkStream> {
    /// Create a new [PartStream] from the given [ChunkStream]
    ///
    /// Will fail if the [ChunkStream] was already iterated.
    pub fn from_chunk_stream(chunk_stream: ChunkStream) -> Result<Self, CondowError> {
        if !chunk_stream.is_fresh() {
            return Err(CondowError::new_other(
                "chunk stream already iterated".to_string(),
            ));
        }
        let bytes_hint = chunk_stream.bytes_hint();
        Ok(Self::new(chunk_stream, bytes_hint))
    }
}

impl<St: Stream<Item = ChunkStreamItem>> Stream for PartStream<St> {
    type Item = PartStreamItem;

    fn poll_next(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        if self.is_closed {
            return Poll::Ready(None);
        }

        let this = self.project();

        let next = ready!(this.stream.poll_next(cx));
        match next {
            Some(Ok(chunk)) => {
                if chunk.chunk_index == 0
                    && chunk.is_last()
                    && chunk.part_index == *this.next_part_idx
                {
                    this.bytes_hint.reduce_by(chunk.len());
                    *this.next_part_idx += 1;
                    Poll::Ready(Some(Ok(Part {
                        part_index: chunk.part_index,
                        blob_offset: chunk.blob_offset,
                        range_offset: chunk.range_offset,
                        chunks: vec![chunk.bytes],
                    })))
                } else {
                    let entry = this
                        .collected_parts
                        .entry(chunk.part_index)
                        .or_insert_with(|| PartEntry {
                            part_index: chunk.part_index,
                            blob_offset: chunk.blob_offset,
                            range_offset: chunk.range_offset,
                            chunks: vec![],
                            is_complete: false,
                        });
                    entry.is_complete = chunk.is_last();
                    entry.chunks.push(chunk.bytes);

                    if let Some(entry) = this.collected_parts.get(this.next_part_idx) {
                        if entry.is_complete {
                            let PartEntry {
                                part_index,
                                blob_offset: file_offset,
                                range_offset,
                                chunks,
                                ..
                            } = this.collected_parts.remove(this.next_part_idx).unwrap();
                            this.bytes_hint
                                .reduce_by(chunks.iter().map(|c| c.len()).sum());
                            *this.next_part_idx += 1;
                            Poll::Ready(Some(Ok(Part {
                                part_index,
                                blob_offset: file_offset,
                                range_offset,
                                chunks,
                            })))
                        } else {
                            cx.waker().clone().wake();
                            Poll::Pending
                        }
                    } else {
                        cx.waker().clone().wake();
                        Poll::Pending
                    }
                }
            }
            Some(Err(err)) => {
                *this.is_closed = true;
                *this.bytes_hint = BytesHint::new_exact(0);
                Poll::Ready(Some(Err(err)))
            }
            None => {
                if let Some(next) = this.collected_parts.remove(this.next_part_idx) {
                    *this.next_part_idx += 1;
                    this.bytes_hint
                        .reduce_by(next.chunks.iter().map(|c| c.len()).sum());
                    Poll::Ready(Some(Ok(Part {
                        part_index: next.part_index,
                        blob_offset: next.blob_offset,
                        range_offset: next.range_offset,
                        chunks: next.chunks,
                    })))
                } else {
                    *this.is_closed = true;
                    *this.bytes_hint = BytesHint::new_exact(0);
                    Poll::Ready(None)
                }
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, None)
    }
}

#[cfg(test)]
mod tests {
    use futures::StreamExt;

    use crate::test_utils::create_part_stream;

    #[tokio::test]
    async fn check_iter_one_part_one_chunk() {
        let (mut stream, expected) = create_part_stream(1, 1, true, Some(10));

        let mut collected = Vec::new();

        while let Some(next) = stream.next().await {
            let next = next.unwrap();

            next.chunks.iter().flatten().for_each(|&v| {
                collected.push(v);
            });
        }

        assert_eq!(collected, expected);
    }

    #[tokio::test]
    async fn check_iter_one_part_two_chunks() {
        let (mut stream, expected) = create_part_stream(1, 2, true, Some(10));

        let mut collected = Vec::new();

        while let Some(next) = stream.next().await {
            let next = next.unwrap();

            next.chunks.iter().flatten().for_each(|&v| {
                collected.push(v);
            });
        }

        assert_eq!(collected, expected);
    }

    #[tokio::test]
    async fn check_iter_two_parts_one_chunk() {
        let (mut stream, expected) = create_part_stream(2, 1, true, Some(10));

        let mut collected = Vec::new();

        while let Some(next) = stream.next().await {
            let next = next.unwrap();

            next.chunks.iter().flatten().for_each(|&v| {
                collected.push(v);
            });
        }

        assert_eq!(collected, expected);
    }

    #[tokio::test]
    async fn check_iter_multiple() {
        for parts in 1..10 {
            for chunks in 1..10 {
                let (mut stream, expected) = create_part_stream(parts, chunks, true, Some(10));

                let mut collected = Vec::new();

                while let Some(next) = stream.next().await {
                    let next = next.unwrap();

                    next.chunks.iter().flatten().for_each(|&v| {
                        collected.push(v);
                    });
                }

                assert_eq!(collected, expected);
            }
        }
    }

    mod into_vec {
        use crate::test_utils::create_part_stream;

        #[tokio::test]
        async fn with_exact_hint() {
            for parts in 1..10 {
                for chunks in 1..10 {
                    let (stream, expected) = create_part_stream(parts, chunks, true, Some(10));

                    let result = stream.into_vec().await.unwrap();

                    assert_eq!(result, expected);
                }
            }
        }

        #[tokio::test]
        async fn with_at_max_hint() {
            for parts in 1..10 {
                for chunks in 1..10 {
                    let (stream, expected) = create_part_stream(parts, chunks, false, Some(10));

                    let result = stream.into_vec().await.unwrap();

                    assert_eq!(result, expected);
                }
            }
        }
    }
}