-
Notifications
You must be signed in to change notification settings - Fork 224
Expand file tree
/
Copy patharchive_index.rs
More file actions
1600 lines (1389 loc) · 55.3 KB
/
archive_index.rs
File metadata and controls
1600 lines (1389 loc) · 55.3 KB
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::{
PathNotFoundError, blob::StreamingBlob, config::ArchiveIndexCacheConfig, types::FileRange,
utils::file_list::walk_dir_recursive,
};
use anyhow::{Context as _, Result, anyhow, bail};
use docs_rs_opentelemetry::AnyMeterProvider;
use docs_rs_types::{BuildId, CompressionAlgorithm};
use docs_rs_utils::spawn_blocking;
use futures_util::TryStreamExt as _;
use moka::future::Cache as MokaCache;
use opentelemetry::{
KeyValue,
metrics::{Counter, Gauge, Histogram},
};
use sqlx::{ConnectOptions as _, Connection as _, QueryBuilder, Row as _, Sqlite};
use std::{
future::Future,
path::{Path, PathBuf},
pin::Pin,
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
time::Duration,
};
use tokio::{
fs,
io::{self, AsyncRead, AsyncSeek, AsyncWriteExt as _},
sync::mpsc,
task::JoinHandle,
};
use tokio_util::io::SyncIoBridge;
use tracing::{debug, error, info, instrument, trace, warn};
pub(crate) const ARCHIVE_INDEX_FILE_EXTENSION: &str = "index";
/// dummy size we assume in case of errors
const DUMMY_FILE_SIZE: u64 = 1024 * 1024; // 1 MiB
/// self-repair attempts
const FIND_ATTEMPTS: usize = 3;
#[derive(Debug)]
struct Metrics {
// calls to find an entry in the local cache
find_calls: Counter<u64>,
// local cache eviction
evicted_entries: Counter<u64>,
evicted_bytes_total: Counter<u64>,
evicted_entry_size: Histogram<u64>,
// local cache misses / downloads & bytes
// includes & doesn't differentiate retries / repairs for now
downloads: Counter<u64>,
downloaded_bytes: Counter<u64>,
downloaded_entry_size: Histogram<u64>,
// full cache size (count / bytes)
weighted_size_bytes: Gauge<u64>,
entry_count: Gauge<u64>,
}
impl Metrics {
fn new(meter_provider: &AnyMeterProvider) -> Self {
let meter = meter_provider.meter("storage");
const PREFIX: &str = "docsrs.storage.archive_index_cache";
const KIB: f64 = 1024.0;
const MIB: f64 = 1024.0 * KIB;
const GIB: f64 = 1024.0 * MIB;
let entry_size_boundaries = vec![
500.0 * KIB,
1.0 * MIB,
2.0 * MIB,
4.0 * MIB,
8.0 * MIB,
16.0 * MIB,
32.0 * MIB,
64.0 * MIB,
128.0 * MIB,
256.0 * MIB,
512.0 * MIB,
1.0 * GIB,
2.0 * GIB,
4.0 * GIB,
8.0 * GIB,
10.0 * GIB,
];
Self {
find_calls: meter
.u64_counter(format!("{PREFIX}.find_total"))
.with_unit("1")
.build(),
downloads: meter
.u64_counter(format!("{PREFIX}.download_total"))
.with_unit("1")
.build(),
downloaded_bytes: meter
.u64_counter(format!("{PREFIX}.download_bytes_total"))
.with_unit("By")
.build(),
evicted_entries: meter
.u64_counter(format!("{PREFIX}.eviction_total"))
.with_unit("1")
.build(),
evicted_bytes_total: meter
.u64_counter(format!("{PREFIX}.evicted_bytes_total"))
.with_unit("By")
.build(),
evicted_entry_size: meter
.u64_histogram(format!("{PREFIX}.evicted_entry_size"))
.with_unit("By")
.with_boundaries(entry_size_boundaries.clone())
.build(),
downloaded_entry_size: meter
.u64_histogram(format!("{PREFIX}.downloaded_entry_size"))
.with_unit("By")
.with_boundaries(entry_size_boundaries)
.build(),
weighted_size_bytes: meter
.u64_gauge(format!("{PREFIX}.weighted_size_bytes"))
.with_unit("By")
.build(),
entry_count: meter
.u64_gauge(format!("{PREFIX}.entry_count"))
.with_unit("1")
.build(),
}
}
}
#[derive(PartialEq, Eq, Debug)]
pub(crate) struct FileInfo {
range: FileRange,
compression: CompressionAlgorithm,
}
struct Entry {
// file size of the local sqlite database.
// Will be used to "weigh" cache entries, so that the cache can evict based on
// total size of cached files instead of number of entries.
file_size_kib: u32,
}
impl Entry {
fn from_size(file_size: u64) -> Self {
let file_size_kib = file_size.div_ceil(1024).max(1).min(u32::MAX as u64) as u32;
Self { file_size_kib }
}
async fn from_path(path: impl AsRef<Path>) -> Self {
let path = path.as_ref();
Self::from_size(match fs::metadata(&path).await {
Ok(meta) => meta.len(),
Err(err) => {
warn!(
?err,
?path,
"failed to get metadata for local archive index file, using dummy size for cache eviction"
);
DUMMY_FILE_SIZE
}
})
}
}
type CacheManager = MokaCache<PathBuf, Arc<Entry>>;
/// Local archive index cache.
///
/// Note: "last access" times for cache entries reset on each server startup
/// (the moka cache starts empty and gets backfilled from disk without
/// preserving prior access timestamps). This means TTI-based eviction is
/// uninformed until real traffic re-establishes usage patterns.
///
/// This is acceptable because:
/// - Builds happen infrequently (every couple of months), so cached index
/// data stays valid for a long time. Serving it for an extra TTL window
/// after a restart is harmless.
/// - moka's TinyLFU-based eviction policy adapts quickly once traffic
/// resumes.
/// - Persisting access timestamps would add significant complexity
/// (moka doesn't support injecting custom timestamps on insert) for
/// marginal benefit.
pub(crate) struct Cache {
config: Arc<ArchiveIndexCacheConfig>,
/// Tracks locally cached archive indices and coordinates their initialization & invalidation.
manager: CacheManager,
metrics: Arc<Metrics>,
background_tasks: Vec<JoinHandle<()>>,
}
pub(crate) trait Downloader {
fn fetch_archive_index<'a>(
&'a self,
remote_index_path: &'a str,
) -> Pin<Box<dyn Future<Output = Result<StreamingBlob>> + Send + 'a>>;
}
impl Cache {
/// create a new archive index cache.
///
/// Also starts a background task that will backfill the in-memory cache management based
/// on the local files that are already.
pub(crate) async fn new(
config: Arc<ArchiveIndexCacheConfig>,
meter_provider: &AnyMeterProvider,
) -> Result<Self> {
let mut cache = Self::new_inner(config.clone(), meter_provider).await?;
cache.background_tasks.push(tokio::spawn({
let manager = cache.manager.clone();
async move {
if let Err(err) = Self::backfill_cache_manager(config, manager).await {
error!(?err, "failed to backfill archive index cache manager");
}
}
}));
Ok(cache)
}
/// create a new archive index cache, and directly backfill the in-memory structures.
///
/// Only for testing.
#[cfg(test)]
async fn new_with_backfill(
config: Arc<ArchiveIndexCacheConfig>,
meter_provider: &AnyMeterProvider,
) -> Result<Self> {
let cache = Self::new_inner(config.clone(), meter_provider).await?;
Self::backfill_cache_manager(config, cache.manager.clone())
.await
.context("failed to backfill archive index cache manager")?;
Ok(cache)
}
async fn new_inner(
config: Arc<ArchiveIndexCacheConfig>,
meter_provider: &AnyMeterProvider,
) -> Result<Self> {
fs::create_dir_all(&config.path)
.await
.context("failed to create archive index cache directory")?;
let metrics = Arc::new(Metrics::new(meter_provider));
let metrics_for_eviction = metrics.clone();
let manager = CacheManager::builder()
.initial_capacity(config.expected_count)
// Time to idle (TTI): A cached entry will be expired after
// the specified duration past from get or insert.
// We don't set TTL (time to live), which would be just time-after-insert.
.time_to_idle(config.ttl)
// we weigh each cache entry by the file size of the sqlite database.
// The max size of the cache for all of docs.rs is 500 GiB at the time of writing.
// In KiB, this would be around 500k, which makes KiB the right unit.
// Anything bigger (like MiB) would mean that we count smaller dbs than 1 MiB as if
// they were 1 MiB big.
.weigher(|_key: &PathBuf, entry: &Arc<Entry>| -> u32 { entry.file_size_kib })
// max capacity
// not entries, but _weighted entries_.
// with the weight fn from above, the max capacity is a storage size value.
.max_capacity(config.max_size_mb * 1024)
// the eviction listener is called when moka evicts a cache entry.
// In this case we want to delete the corresponding local files.
.eviction_listener(move |path, entry, reason| {
let path = path.to_path_buf();
let metrics = metrics_for_eviction.clone();
// The spawned task means file deletion is deferred. See the
// "benign race with the eviction listener" comment in `find_inner`
// for why this is acceptable.
tokio::spawn(async move {
let reason = format!("{reason:?}");
let evicted_bytes = entry.file_size_kib as u64 * 1024;
let reason_attr = [KeyValue::new("cause", reason.clone())];
metrics.evicted_entries.add(1, &reason_attr);
metrics.evicted_bytes_total.add(evicted_bytes, &reason_attr);
metrics
.evicted_entry_size
.record(evicted_bytes, &reason_attr);
trace!(
?path,
?reason_attr,
"evicting local archive index file from cache"
);
if let Err(err) = Self::remove_local_index(&path).await {
error!(
?err,
?path,
?reason,
"failed to remove local archive index file on cache eviction"
);
}
});
})
.build();
let handle = tokio::spawn({
let manager = manager.clone();
let metrics = metrics.clone();
// moka will also run maintenance tasks itself, but I want to force this
// at least every 30 seconds.
//
// We also use this background task to gather metrics.
async move {
let mut interval = tokio::time::interval(Duration::from_secs(30));
loop {
interval.tick().await;
debug!("running pending tasks for archive index cache manager");
manager.run_pending_tasks().await;
debug!("collect cache size metrics");
metrics.entry_count.record(manager.entry_count(), &[]);
metrics
.weighted_size_bytes
.record(manager.weighted_size() * 1024, &[]);
}
}
});
let cache = Self {
manager,
config,
metrics,
background_tasks: vec![handle],
};
Ok(cache)
}
/// run any pending tasks, like evictions that need to delete local files.
#[cfg(test)]
async fn flush(&self) -> Result<()> {
self.manager.run_pending_tasks().await;
Ok(())
}
#[cfg(test)]
async fn backfill(&self) -> Result<()> {
Self::backfill_cache_manager(self.config.clone(), self.manager.clone()).await
}
/// backfill the in memory cache management based on the local files that are already
/// present on disk.
///
/// Should be needed only once after server startup.
///
/// While this is running, our `find_inner` & `download_archive_index` logic will just
/// fill it itself.
///
/// Concurrency is set to a lower value intentionally so we don't put
/// too much i/o pressure onto the disk.
#[instrument(skip_all)]
async fn backfill_cache_manager(
config: Arc<ArchiveIndexCacheConfig>,
manager: CacheManager,
) -> Result<()> {
info!(path=%config.path.display(), "starting cache-manager backfill from local directory");
let inserted = Arc::new(AtomicU64::new(0));
walk_dir_recursive(&config.path)
.err_into::<anyhow::Error>()
.try_for_each_concurrent(Some(4), |item| {
let manager = manager.clone();
let inserted = inserted.clone();
async move {
let path = item.absolute;
if path.extension().and_then(|ext| ext.to_str())
== Some(ARCHIVE_INDEX_FILE_EXTENSION)
{
let entry = manager
.entry(path)
.or_insert_with(async {
Arc::new(Entry::from_size(item.metadata.len()))
})
.await;
if entry.is_fresh() {
inserted.fetch_add(1, Ordering::Relaxed);
}
}
Ok(())
}
})
.await?;
info!(
inserted_count = inserted.load(Ordering::Relaxed),
"finished cache-manager backfill"
);
Ok(())
}
async fn remove_local_index(path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
for ext in &["wal", "shm"] {
let to_delete = path.with_extension(format!("{ARCHIVE_INDEX_FILE_EXTENSION}-{ext}"));
let _ = fs::remove_file(&to_delete).await;
}
if let Err(err) = fs::remove_file(&path).await
&& err.kind() != io::ErrorKind::NotFound
{
Err(err.into())
} else {
Ok(())
}
}
fn local_index_path(&self, archive_path: &str, latest_build_id: Option<BuildId>) -> PathBuf {
self.config.path.join(format!(
"{archive_path}.{}.{ARCHIVE_INDEX_FILE_EXTENSION}",
latest_build_id.map(|id| id.0).unwrap_or(0)
))
}
/// purge a single archive index file
pub(crate) async fn purge(
&self,
archive_path: &str,
latest_build_id: Option<BuildId>,
) -> Result<()> {
let local_index_path = self.local_index_path(archive_path, latest_build_id);
Self::remove_local_index(&local_index_path).await?;
self.manager.invalidate(&local_index_path).await;
Ok(())
}
async fn find_inner(
&self,
archive_path: &str,
latest_build_id: Option<BuildId>,
path_in_archive: &str,
downloader: &impl Downloader,
) -> Result<Option<FileInfo>> {
let local_index_path = self.local_index_path(archive_path, latest_build_id);
// fast path: try to use whatever is there, no locking
let force_redownload = match find_in_file(&local_index_path, path_in_archive).await {
Ok(res) => {
// Keep moka's recency/frequency view in sync with successful fast-path
// file lookups so TTI and admission decisions reflect real usage.
if self.manager.get(&local_index_path).await.is_none() {
let entry_path = local_index_path.clone();
self.manager
.entry(local_index_path.clone())
.or_insert_with(
async move { Arc::new(Entry::from_path(&entry_path).await) },
)
.await;
}
return Ok(res);
}
Err(err) => {
let force_redownload = !err.is::<PathNotFoundError>();
debug!(?err, "archive index lookup failed, will try repair.");
force_redownload
}
};
let remote_index_path = format!("{archive_path}.{ARCHIVE_INDEX_FILE_EXTENSION}");
// moka will coalesce all concurrent calls to try_get_with_by_ref with the same key
// into a single call to the async closure.
// https://docs.rs/moka/0.12.14/moka/future/struct.Cache.html#concurrent-calls-on-the-same-key
// So we don't need any locking here to prevent multiple downloads for the same
// missing archive index.
if let Err(arc_err) = self
.manager
.try_get_with_by_ref(&local_index_path, async {
// NOTE: benign race with the eviction listener.
//
// When moka evicts an entry (time/size pressure), it removes it from the
// cache immediately but runs the eviction listener later (via a spawned
// tokio task that deletes the local file).
//
// If a new request arrives between the cache removal and the file deletion:
// 1. Cache miss → we enter this closure.
// 2. `try_exists` → true (file not deleted yet).
// 3. We re-insert the existing file into the cache.
// 4. The eviction listener's spawned task then runs and deletes the file
// out from under us.
// 5. The next `find` call fails on the fast path (file gone), falls back
// into this closure, sees `try_exists` → false, and re-downloads.
//
// Net impact: one request pays the cost of an extra S3 download. No error
// is visible to the user since the self-repair logic handles it.
let entry = if !force_redownload && fs::try_exists(&local_index_path).await? {
// after server startup we might have local indexes that don't
// yet exist in our cache manager.
// So we only need to download if the file doesn't exist.
Entry::from_path(&local_index_path).await
} else {
if force_redownload {
Self::remove_local_index(&local_index_path).await?;
}
Entry::from_size(
self.download_archive_index(
downloader,
&local_index_path,
&remote_index_path,
)
.await?,
)
};
Ok::<_, anyhow::Error>(Arc::new(entry))
})
.await
{
// We can't convert this Arc<Error> into the inner error type.
// See https://github.com/moka-rs/moka/issues/497
// But since some callers are specifically checking
// ::is<PathNotFoundError> to differentiate other errors from
// the "not found" case, we want to preserve that information
// if it was the cause of the error.
//
// This mean all error types that we later want to use with ::is<> or
// ::downcast<> have to be mentioned here.
//
// While we could also migrate to a custom enum error type, this would
// only be really nice when the whole storage lib uses is. Otherwise
// we'll end up with some hardcoded conversions again.
// So I can leave it as-is for now.
if arc_err.is::<PathNotFoundError>() {
return Ok(None);
} else {
return Err(anyhow!(arc_err));
}
}
// Final attempt: if this still fails, bubble the error.
find_in_file(local_index_path, path_in_archive).await
}
/// Find the file metadata needed to fetch a certain path inside a remote archive.
/// Will try to use a local cache of the index file, and otherwise download it
/// from storage.
#[instrument(skip(self, downloader))]
pub(crate) async fn find(
&self,
archive_path: &str,
latest_build_id: Option<BuildId>,
path_in_archive: &str,
downloader: &impl Downloader,
) -> Result<Option<FileInfo>> {
for attempt in 1..=FIND_ATTEMPTS {
match self
.find_inner(archive_path, latest_build_id, path_in_archive, downloader)
.await
{
Ok(file_info) => {
self.metrics.find_calls.add(
1,
&[
KeyValue::new("attempt", attempt.to_string()),
KeyValue::new("outcome", "success"),
],
);
return Ok(file_info);
}
Err(err) if attempt < FIND_ATTEMPTS => {
warn!(
?err,
%attempt,
"error resolving archive index, purging local cache and retrying"
);
self.purge(archive_path, latest_build_id).await?;
}
Err(err) => {
self.metrics.find_calls.add(
1,
&[
KeyValue::new("attempt", attempt.to_string()),
KeyValue::new("outcome", "error"),
],
);
return Err(err);
}
}
}
unreachable!("find retry loop exited unexpectedly");
}
#[instrument(skip(self, downloader))]
pub(crate) async fn download_archive_index(
&self,
downloader: &impl Downloader,
local_index_path: &Path,
remote_index_path: &str,
) -> Result<u64> {
let parent = local_index_path
.parent()
.ok_or_else(|| anyhow!("index path without parent"))?
.to_path_buf();
fs::create_dir_all(&parent).await?;
// Create a unique temp file in the cache folder.
let (temp_file, mut temp_path) = spawn_blocking({
let folder = self.config.path.clone();
move || -> Result<_> { tempfile::NamedTempFile::new_in(&folder).map_err(Into::into) }
})
.await?
.into_parts();
// Download into temp file.
let mut temp_file = fs::File::from_std(temp_file);
let mut stream = downloader
.fetch_archive_index(remote_index_path)
.await?
.content;
let copied = io::copy(&mut stream, &mut temp_file).await?;
temp_file.flush().await?;
// Publish atomically.
// Will replace any existing file.
fs::rename(&temp_path, local_index_path).await?;
temp_path.disable_cleanup(true);
self.metrics.downloads.add(1, &[]);
self.metrics.downloaded_bytes.add(copied, &[]);
self.metrics.downloaded_entry_size.record(copied, &[]);
Ok(copied)
}
}
impl Drop for Cache {
fn drop(&mut self) {
for task in &self.background_tasks {
task.abort();
}
}
}
impl FileInfo {
pub(crate) fn range(&self) -> FileRange {
self.range.clone()
}
pub(crate) fn compression(&self) -> CompressionAlgorithm {
self.compression
}
}
/// creates a new empty SQLite database, and returns a configured connection
/// pool to connect to the DB.
/// Any existing DB at the given path will be deleted first.
async fn sqlite_create<P: AsRef<Path>>(path: P) -> Result<sqlx::SqliteConnection> {
let path = path.as_ref();
if fs::try_exists(&path).await? {
fs::remove_file(path).await?;
}
sqlx::sqlite::SqliteConnectOptions::new()
.filename(path)
.read_only(false)
.pragma("synchronous", "full")
.create_if_missing(true)
.connect()
.await
.map_err(Into::into)
}
/// open existing SQLite database, return a configured connection poll
/// to connect to the DB.
/// Will error when the database doesn't exist at that path.
async fn sqlite_open<P: AsRef<Path>>(path: P) -> Result<sqlx::SqliteConnection> {
sqlx::sqlite::SqliteConnectOptions::new()
.filename(path)
.read_only(true)
.immutable(true)
.pragma("synchronous", "off") // not needed for readonly db
.pragma("temp_store", "MEMORY")
.pragma("query_only", "ON")
.pragma("mmap_size", "536870912") // 512 MiB
.pragma("cache_size", "-4096") // 4 MiB
.serialized(false) // same as OPEN_NOMUTEX
.create_if_missing(false)
.connect()
.await
.map_err(Into::into)
}
/// create an archive index based on a zipfile.
///
/// Will delete the destination file if it already exists.
#[instrument(skip(zipfile))]
pub(crate) async fn create<R, P>(zipfile: R, destination: P) -> Result<R>
where
R: AsyncRead + AsyncSeek + Unpin + Send + 'static,
P: AsRef<Path> + std::fmt::Debug,
{
let mut conn = sqlite_create(destination).await?;
let mut tx = conn.begin().await?;
sqlx::query(
r#"
CREATE TABLE files (
id INTEGER PRIMARY KEY,
path TEXT UNIQUE,
start INTEGER,
end INTEGER,
compression INTEGER
);
"#,
)
.execute(&mut *tx)
.await?;
let compression_bzip = CompressionAlgorithm::Bzip2 as i32;
let (tx_entries, mut rx_entries) = mpsc::channel::<(String, u64, u64, i32)>(1000);
let zip_task = spawn_blocking(move || {
let mut bridge = SyncIoBridge::new(zipfile);
let mut archive = zip::ZipArchive::new(&mut bridge)?;
for i in 0..archive.len() {
let entry = archive.by_index(i)?;
let start = entry
.data_start()
.ok_or_else(|| anyhow!("missing data_start in zip directory"))?;
let end = start + entry.compressed_size() - 1;
let compression_raw = match entry.compression() {
zip::CompressionMethod::Bzip2 => compression_bzip,
c => bail!("unsupported compression algorithm {} in zip-file", c),
};
tx_entries
.blocking_send((entry.name().to_string(), start, end, compression_raw))
.map_err(|_| anyhow!("archive index receiver dropped"))?;
}
drop(archive);
Ok(bridge.into_inner())
});
const CHUNKS: usize = 1000;
let mut chunk = Vec::with_capacity(CHUNKS);
loop {
let received = rx_entries.recv_many(&mut chunk, CHUNKS).await;
if received == 0 {
break;
}
let mut insert_stmt =
QueryBuilder::<Sqlite>::new("INSERT INTO files (path, start, end, compression) ");
insert_stmt.push_values(
chunk.drain(..),
|mut b, (path, start, end, compression_raw)| {
b.push_bind(path)
.push_bind(start as i64)
.push_bind(end as i64)
.push_bind(compression_raw);
},
);
insert_stmt
.build()
.persistent(false)
.execute(&mut *tx)
.await?;
}
let zipfile = zip_task.await?;
sqlx::query("CREATE INDEX idx_files_path ON files (path);")
.execute(&mut *tx)
.await?;
// Commit the transaction before VACUUM (VACUUM cannot run inside a transaction)
tx.commit().await?;
// VACUUM outside the transaction
sqlx::query("VACUUM").execute(&mut conn).await?;
Ok(zipfile)
}
async fn find_in_sqlite_index<'e, E>(executor: E, search_for: &str) -> Result<Option<FileInfo>>
where
E: sqlx::Executor<'e, Database = sqlx::Sqlite>,
{
let row = sqlx::query(
"
SELECT start, end, compression
FROM files
WHERE path = ?
",
)
.bind(search_for)
.fetch_optional(executor)
.await
.context("error fetching SQLite data")?;
if let Some(row) = row {
let start: u64 = row.try_get(0)?;
let end: u64 = row.try_get(1)?;
let compression_raw: i32 = row.try_get(2)?;
Ok(Some(FileInfo {
range: start..=end,
compression: compression_raw.try_into().map_err(|value| {
anyhow::anyhow!(format!(
"invalid compression algorithm '{value}' in database"
))
})?,
}))
} else {
Ok(None)
}
}
#[instrument]
pub(crate) async fn find_in_file<P>(
archive_index_path: P,
search_for: &str,
) -> Result<Option<FileInfo>>
where
P: AsRef<Path> + std::fmt::Debug,
{
let mut conn = sqlite_open(archive_index_path).await?;
find_in_sqlite_index(&mut conn, search_for).await
}
#[cfg(test)]
mod tests {
use super::*;
use crate::blob::StreamingBlob;
use chrono::Utc;
use docs_rs_config::AppConfig as _;
use docs_rs_opentelemetry::testing::TestMetrics;
use sqlx::error::DatabaseError as _;
use std::{collections::HashMap, io::Cursor, ops::Deref, pin::Pin, sync::Arc};
use zip::write::SimpleFileOptions;
async fn create_test_archive(file_count: u32) -> Result<fs::File> {
spawn_blocking(move || {
use std::io::Write as _;
let tf = tempfile::tempfile()?;
let objectcontent: Vec<u8> = (0..255).collect();
let mut archive = zip::ZipWriter::new(tf);
for i in 0..file_count {
archive.start_file(
format!("testfile{i}"),
SimpleFileOptions::default().compression_method(zip::CompressionMethod::Bzip2),
)?;
archive.write_all(&objectcontent)?;
}
Ok(archive.finish()?)
})
.await
.map(fs::File::from_std)
}
struct FakeDownloader {
indices: HashMap<String, Vec<u8>>,
download_count: std::sync::Mutex<HashMap<String, usize>>,
delay: Option<std::time::Duration>,
}
impl FakeDownloader {
fn new() -> Self {
Self {
indices: HashMap::new(),
download_count: std::sync::Mutex::new(HashMap::new()),
delay: None,
}
}
fn with_delay(delay: std::time::Duration) -> Self {
let mut downloader = Self::new();
downloader.delay = Some(delay);
downloader
}
fn download_count(&self, remote_index_path: &str) -> usize {
let download_count = self.download_count.lock().unwrap();
*download_count.get(remote_index_path).unwrap_or(&0)
}
}
impl Downloader for FakeDownloader {
fn fetch_archive_index<'a>(
&'a self,
remote_index_path: &'a str,
) -> Pin<Box<dyn Future<Output = Result<StreamingBlob>> + Send + 'a>> {
Box::pin(async move {
if let Some(delay) = self.delay {
tokio::time::sleep(delay).await;
}
let mut fetch_count = self.download_count.lock().unwrap();
fetch_count
.entry(remote_index_path.to_string())
.and_modify(|count| *count += 1)
.or_insert(1);
let content = self
.indices
.get(remote_index_path)
.cloned()
.ok_or_else(|| anyhow!("missing index fixture for {remote_index_path}"))?;
Ok(StreamingBlob {
path: remote_index_path.to_string(),
mime: mime::APPLICATION_OCTET_STREAM,
date_updated: Utc::now(),
etag: None,
compression: None,
content_length: content.len(),
content: Box::new(Cursor::new(content)),
})
})
}
}
struct FlakyDownloader {
remote_index_path: String,
payload: Vec<u8>,
fail_until: usize,
fetch_count: std::sync::Mutex<usize>,
}
impl FlakyDownloader {
fn new(remote_index_path: String, payload: Vec<u8>, fail_until: usize) -> Self {
Self {
remote_index_path,
payload,
fail_until,
fetch_count: std::sync::Mutex::new(0),
}
}
fn fetch_count(&self) -> usize {
*self.fetch_count.lock().unwrap()
}
}
impl Downloader for FlakyDownloader {
fn fetch_archive_index<'a>(
&'a self,
remote_index_path: &'a str,
) -> Pin<Box<dyn Future<Output = Result<StreamingBlob>> + Send + 'a>> {
Box::pin(async move {
if remote_index_path != self.remote_index_path {
bail!(
"unexpected remote index path: expected {}, got {remote_index_path}",
self.remote_index_path
);
}
let mut fetch_count = self.fetch_count.lock().unwrap();
*fetch_count += 1;
if *fetch_count <= self.fail_until {
bail!("synthetic download failure {fetch_count}");
}
let content = self.payload.clone();
Ok(StreamingBlob {
path: remote_index_path.to_string(),
mime: mime::APPLICATION_OCTET_STREAM,
date_updated: Utc::now(),
etag: None,
compression: None,
content_length: content.len(),
content: Box::new(Cursor::new(content)),
})
})
}
}
struct NotFoundDownloader {
remote_index_path: String,
fetch_count: std::sync::Mutex<usize>,
}
impl NotFoundDownloader {
fn new(remote_index_path: String) -> Self {
Self {
remote_index_path,
fetch_count: std::sync::Mutex::new(0),
}
}
fn fetch_count(&self) -> usize {
*self.fetch_count.lock().unwrap()
}
}
impl Downloader for NotFoundDownloader {
fn fetch_archive_index<'a>(