condow_core 0.18.2

Framework for concurrent downloads
Documentation
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Download requests
//!
//! Builder style APIs to configure individual downloads.

use std::{str::FromStr, sync::Arc};

use futures::{
    future::{self, BoxFuture},
    FutureExt, TryStreamExt,
};

use crate::{
    condow_client::IgnoreLocation,
    config::Config,
    errors::CondowError,
    probe::Probe,
    reader::{BytesAsyncReader, FetchAheadMode, RandomAccessReader},
    streams::BytesStream,
    ChunkStream, DownloadRange, InclusiveRange, OrderedChunkStream,
};

pub(crate) trait RequestAdapter<L>: Send + Sync + 'static {
    fn bytes(&self, location: L, params: Params)
        -> BoxFuture<'_, Result<BytesStream, CondowError>>;
    fn chunks(
        &self,
        location: L,
        params: Params,
    ) -> BoxFuture<'_, Result<ChunkStream, CondowError>>;
    fn size(&self, location: L, params: Params) -> BoxFuture<'_, Result<u64, CondowError>>;
}

/// A request for a download where the location is not yet known
///
/// The default is to download the complete BLOB.
///
/// A location to download from must be provided to actually download
/// from a remote location.
///
/// This can only directly download if the type of the location is [IgnoreLocation]
/// which probably only makes sense while testing.
pub struct RequestNoLocation<L> {
    adapter: Box<dyn RequestAdapter<L>>,
    params: Params,
}

impl<L> RequestNoLocation<L> {
    pub(crate) fn new<A>(adapter: A, config: Config) -> Self
    where
        A: RequestAdapter<L>,
    {
        Self {
            adapter: Box::new(adapter),
            params: Params {
                probe: None,
                range: (..).into(),
                config,
                trusted_blob_size: None,
            },
        }
    }

    /// Specify the location to download the Blob from
    pub fn at<LL: Into<L>>(self, location: LL) -> Request<L> {
        Request {
            adapter: self.adapter,
            location: location.into(),
            params: self.params,
        }
    }

    /// Specify the location to download the BLOB from
    ///
    /// Fails if `location` is not convertable to `Self::L`.
    pub fn try_at<LL>(self, location: LL) -> Result<Request<L>, CondowError>
    where
        LL: TryInto<L>,
        LL::Error: std::error::Error + Send + Sync + 'static,
    {
        Ok(Request {
            adapter: self.adapter,
            location: location.try_into().map_err(|err| {
                CondowError::new_other(format!("invalid location - {err}")).with_source(err)
            })?,
            params: self.params,
        })
    }

    /// Specify the location as a string slice to download the BLOB from
    ///
    /// Fails if `location` is not parsable.
    pub fn try_at_str(self, location: &str) -> Result<Request<L>, CondowError>
    where
        L: FromStr,
        <L as FromStr>::Err: std::error::Error + Send + Sync + 'static,
    {
        Ok(Request {
            adapter: self.adapter,
            location: location.parse().map_err(|err| {
                CondowError::new_other(format!("invalid location: {location}")).with_source(err)
            })?,
            params: self.params,
        })
    }

    /// Specify the range to download
    pub fn range<DR: Into<DownloadRange>>(mut self, range: DR) -> Self {
        self.params.range = range.into();
        self
    }

    /// Specify the total size of the BLOB.
    ///
    /// This will prevent condow from querying the size of the BLOB.
    /// The supplied value must be correct.
    pub fn trusted_blob_size(mut self, size: u64) -> Self {
        self.params.trusted_blob_size = Some(size);
        self
    }

    /// Attach a [Probe] to the download
    pub fn probe(mut self, probe: Arc<dyn Probe>) -> Self {
        self.params.probe = Some(probe);
        self
    }

    /// Override the configuration for this request
    pub fn reconfigure<F>(mut self, mut reconfigure: F) -> Self
    where
        F: FnMut(Config) -> Config,
    {
        self.params.config = reconfigure(self.params.config);
        self
    }
}

impl RequestNoLocation<IgnoreLocation> {
    /// Download chunks of bytes
    ///
    /// Provided mainly for testing.
    ///
    pub async fn download(self) -> Result<BytesStream, CondowError> {
        self.at(IgnoreLocation).download().await
    }

    /// Download as an [OrderedChunkStream]
    ///
    /// Provided mainly for testing.
    pub async fn download_chunks_ordered(self) -> Result<OrderedChunkStream, CondowError> {
        self.at(IgnoreLocation).download_chunks_ordered().await
    }

    /// Download as a [ChunkStream]
    ///
    /// Provided mainly for testing.
    pub async fn download_chunks_unordered(self) -> Result<ChunkStream, CondowError> {
        self.at(IgnoreLocation).download_chunks_unordered().await
    }

    /// Downloads into a freshly allocated [Vec]
    ///
    /// Provided mainly for testing.
    pub async fn download_into_vec(self) -> Result<Vec<u8>, CondowError> {
        let stream = self.download_chunks_unordered().await?;
        stream.into_vec().await
    }

    /// Writes all received bytes into the provided buffer
    ///
    /// Fails if the buffer is too small.
    ///
    /// Provided mainly for testing.
    pub async fn download_into_buffer(self, buffer: &mut [u8]) -> Result<usize, CondowError> {
        let stream = self.download_chunks_unordered().await?;
        stream.write_buffer(buffer).await
    }

    /// Returns an [AsyncRead] which reads over the bytes of the stream
    ///
    /// Provided mainly for testing.
    pub async fn reader(self) -> Result<BytesAsyncReader, CondowError> {
        let stream = self.download_chunks_ordered().await?.into_bytes_stream();
        Ok(BytesAsyncReader::new(stream))
    }

    /// Returns a builder for a [RandomAccessReader] which implements [AsyncRead] and [AsyncSeek].
    ///
    /// To create a random access reader the size of the BLOB must be known.
    /// If `trusted_blob_size` is set that value will be used. Otherwise a request
    /// to get the size of the BLOB is made.
    ///
    /// The seek operations of the reader operate relatively to the downloaded range.
    /// To seek on the complete BLOB the full range should be specified which is also the default.
    pub fn random_access_reader(self) -> RandomAccessReaderBuilder<IgnoreLocation> {
        self.at(IgnoreLocation).random_access_reader()
    }

    /// Pulls the bytes into the void
    ///
    /// Provided mainly for testing.
    pub async fn wc(self) -> Result<(), CondowError> {
        self.download_chunks_unordered()
            .await?
            .try_for_each(|_| future::ok(()))
            .await?;
        Ok(())
    }
}

/// A request for a download from a specific location
///
/// The default is to download the complete BLOB.
pub struct Request<L> {
    adapter: Box<dyn RequestAdapter<L>>,
    location: L,
    params: Params,
}

impl<L> Request<L>
where
    L: Send + Sync + 'static,
{
    /// Specify the location to download the Blob from
    pub fn at<LL: Into<L>>(mut self, location: LL) -> Self {
        self.location = location.into();
        self
    }

    /// Specify the range to download
    pub fn range<DR: Into<DownloadRange>>(mut self, range: DR) -> Self {
        self.params.range = range.into();
        self
    }

    /// Specify the total size of the BLOB.
    ///
    /// This will prevent condow from querying the size of the BLOB.
    /// The supplied value must be correct.
    pub fn trusted_blob_size(mut self, size: u64) -> Self {
        self.params.trusted_blob_size = Some(size);
        self
    }

    /// Attach a [Probe] to the download
    pub fn probe(mut self, probe: Arc<dyn Probe>) -> Self {
        self.params.probe = Some(probe);
        self
    }

    /// Override the configuration for this request
    pub fn reconfigure<F>(mut self, mut reconfigure: F) -> Self
    where
        F: FnMut(Config) -> Config,
    {
        self.params.config = reconfigure(self.params.config);
        self
    }

    /// Download chunks of bytes
    pub async fn download(self) -> Result<BytesStream, CondowError> {
        self.params
            .config
            .validate()
            .map_err(|err| CondowError::new_other("invalid configuration").with_source(err))?;
        self.adapter.bytes(self.location, self.params).await
    }

    /// Download as an [OrderedChunkStream]
    pub async fn download_chunks_ordered(self) -> Result<OrderedChunkStream, CondowError> {
        OrderedChunkStream::from_chunk_stream(self.download_chunks_unordered().await?)
    }

    /// Download as a [ChunkStream]
    pub async fn download_chunks_unordered(self) -> Result<ChunkStream, CondowError> {
        self.params
            .config
            .validate()
            .map_err(|err| CondowError::new_other("invalid configuration").with_source(err))?;
        self.adapter.chunks(self.location, self.params).await
    }

    /// Downloads into a freshly allocated [Vec]
    pub async fn download_into_vec(self) -> Result<Vec<u8>, CondowError> {
        let stream = self.download_chunks_unordered().await?;
        stream.into_vec().await
    }

    /// Writes all received bytes into the provided buffer
    ///
    /// Fails if the buffer is too small.
    pub async fn download_into_buffer(self, buffer: &mut [u8]) -> Result<usize, CondowError> {
        let stream = self.download_chunks_unordered().await?;
        stream.write_buffer(buffer).await
    }

    /// Returns an [AsyncRead] which reads over the bytes of the stream
    pub async fn reader(self) -> Result<BytesAsyncReader, CondowError> {
        let stream = self.download().await?;
        Ok(BytesAsyncReader::new(stream))
    }

    /// Returns a builder for a [RandomAccessReader] which implements [AsyncRead] and [AsyncSeek].
    ///
    /// To create a random access reader the size of the BLOB must be known.
    /// If `trusted_blob_size` is set that value will be used. Otherwise a request
    /// to get the size of the BLOB is made.
    ///
    /// The seek operations of the reader operate relatively to the downloaded range.
    /// To seek on the complete BLOB the full range should be specified which is also the default.
    pub fn random_access_reader(self) -> RandomAccessReaderBuilder<L> {
        RandomAccessReaderBuilder {
            adapter: self.adapter,
            location: self.location,
            params: self.params,
            fetch_ahead_mode: FetchAheadMode::default(),
        }
    }

    /// Pulls the bytes into the void
    pub async fn wc(self) -> Result<(), CondowError> {
        self.download_chunks_unordered()
            .await?
            .try_for_each(|_| future::ok(()))
            .await?;
        Ok(())
    }
}

pub struct RandomAccessReaderBuilder<L> {
    adapter: Box<dyn RequestAdapter<L>>,
    location: L,
    params: Params,
    fetch_ahead_mode: FetchAheadMode,
}

impl<L> RandomAccessReaderBuilder<L>
where
    L: Clone + Send + Sync + 'static,
{
    /// Specify the location to download the Blob from
    pub fn at<LL: Into<L>>(mut self, location: LL) -> Self {
        self.location = location.into();
        self
    }

    /// Specify the range to the reader operates on.
    ///
    /// The reader to be created can only operate within th ebounds of this range.
    /// By default the whole BLOB is expected to be read from.
    pub fn range<DR: Into<DownloadRange>>(mut self, range: DR) -> Self {
        self.params.range = range.into();
        self
    }

    /// Specify the total size of the BLOB.
    ///
    /// This will prevent condow from querying the size of the BLOB.
    /// The supplied value must be correct.
    pub fn trusted_blob_size(mut self, size: u64) -> Self {
        self.params.trusted_blob_size = Some(size);
        self
    }

    /// Specify the number of bytes to fetch ahead.
    ///
    /// This reduces the number of requests being made.
    /// Eager fetch is not guaranteed and dependent on [EnsureActivePull].
    ///
    /// [EnsureActivePull]:crate::config::EnsureActivePull
    pub fn fetch_ahead_mode<M: Into<FetchAheadMode>>(mut self, mode: M) -> Self {
        self.fetch_ahead_mode = mode.into();
        self
    }

    /// Attach a [Probe] to the reader
    pub fn probe(mut self, probe: Arc<dyn Probe>) -> Self {
        self.params.probe = Some(probe);
        self
    }

    /// Override the configuration downloads
    pub fn reconfigure<F>(mut self, reconfigure: F) -> Self
    where
        F: FnOnce(Config) -> Config,
    {
        self.params.config = reconfigure(self.params.config);
        self
    }

    /// Returns an [AsyncRead] + [AsyncSeek] which reads over the bytes of the BLOB(-range)
    pub async fn finish(self) -> Result<RandomAccessReader, CondowError> {
        let bounds = match self.params.range {
            DownloadRange::Open(or) => {
                let size = if let Some(trusted_size) = self.params.trusted_blob_size {
                    trusted_size
                } else {
                    self.adapter
                        .size(self.location.clone(), self.params.clone())
                        .await?
                };
                if let Some(range) = or.incl_range_from_size(size)? {
                    range
                } else {
                    return Err(CondowError::new_invalid_range(format!(
                        "{or} with blob size {size}"
                    )));
                }
            }
            DownloadRange::Closed(cl) => {
                let range = if let Some(range) = cl.incl_range() {
                    range
                } else {
                    return Err(CondowError::new_invalid_range(format!("{cl}")));
                };

                range.validate()?;

                if let Some(trusted_size) = self.params.trusted_blob_size {
                    if range.end_incl() >= trusted_size {
                        return Err(CondowError::new_invalid_range(format!("{cl}")));
                    }
                }

                range
            }
        };

        let fetch_ahead_mode = self.fetch_ahead_mode;

        let adapter = Arc::new(self.adapter);
        let params = self.params;
        let location = self.location;
        let get_stream_fn = move |range: InclusiveRange| {
            let mut params = params.clone();
            let location = location.clone();
            let adapter = Arc::clone(&adapter);

            params.range = range.into();
            async move {
                Ok(BytesAsyncReader::new(
                    adapter.bytes(location, params).await?,
                ))
            }
            .boxed()
        };

        Ok(RandomAccessReader::new(
            get_stream_fn,
            bounds,
            fetch_ahead_mode,
        ))
    }
}

/// Internal struct to keep common parameters independen of
/// the dispatch mechanism together
#[derive(Clone)]
pub(crate) struct Params {
    pub probe: Option<Arc<dyn Probe>>,
    pub range: DownloadRange,
    pub config: Config,
    pub trusted_blob_size: Option<u64>,
}

#[cfg(test)]
mod tests {
    use futures::{future::BoxFuture, FutureExt};

    use crate::{
        condow_client::InMemoryClient,
        config::{ClientRetryWrapper, Config},
        errors::CondowError,
        machinery,
        request::{Params, RequestAdapter},
        streams::{BytesStream, ChunkStream},
        RequestNoLocation,
    };

    #[tokio::test]
    async fn request_adapter_typed_compiles() {
        let client = InMemoryClient::<i32>::new_static(b"a remote BLOB");
        let config = Config::default();
        let client = ClientRetryWrapper::new(client, config.retries.clone());

        struct FooAdapter {
            client: ClientRetryWrapper<InMemoryClient<i32>>,
        }

        impl RequestAdapter<i32> for FooAdapter {
            fn bytes(
                &self,
                location: i32,
                params: Params,
            ) -> BoxFuture<'_, Result<BytesStream, CondowError>> {
                machinery::download_bytes(
                    self.client.clone(),
                    params.config,
                    location,
                    params.range,
                    (),
                    None,
                )
                .boxed()
            }

            fn chunks(
                &self,
                _location: i32,
                _params: Params,
            ) -> BoxFuture<'_, Result<ChunkStream, CondowError>> {
                unimplemented!()
            }

            fn size(
                &self,
                location: i32,
                _params: Params,
            ) -> BoxFuture<'_, Result<u64, CondowError>> {
                self.client.get_size(location, &()).boxed()
            }
        }

        let adapter = FooAdapter { client };

        let params = Params {
            probe: None,
            range: (1..=10).into(),
            config,
            trusted_blob_size: None,
        };

        let request = RequestNoLocation {
            adapter: Box::new(adapter),
            params,
        };

        let _bytes = request.at(42).download().await.unwrap();
    }

    #[tokio::test]
    async fn request_adapter_str_compiles() {
        let client = InMemoryClient::<i32>::new_static(b"a remote BLOB");
        let config = Config::default();
        let client = ClientRetryWrapper::new(client, config.retries.clone());

        struct FooAdapter {
            client: ClientRetryWrapper<InMemoryClient<i32>>,
        }

        impl RequestAdapter<&str> for FooAdapter {
            fn bytes<'a>(
                &'a self,
                location: &str,
                params: Params,
            ) -> BoxFuture<'a, Result<BytesStream, CondowError>> {
                machinery::download_bytes(
                    self.client.clone(),
                    params.config,
                    location.parse().unwrap(),
                    params.range,
                    (),
                    None,
                )
                .boxed()
            }

            fn chunks<'a>(
                &'a self,
                _location: &str,
                _params: Params,
            ) -> BoxFuture<'a, Result<ChunkStream, CondowError>> {
                unimplemented!()
            }

            fn size<'a>(
                &'a self,
                location: &str,
                _params: Params,
            ) -> BoxFuture<'a, Result<u64, CondowError>> {
                self.client.get_size(location.parse().unwrap(), &()).boxed()
            }
        }

        let adapter = FooAdapter { client };

        let params = Params {
            probe: None,
            range: (1..=10).into(),
            config,
            trusted_blob_size: None,
        };

        let request = RequestNoLocation {
            adapter: Box::new(adapter),
            params,
        };

        let _bytes = request.at("42").download().await.unwrap();
    }
}