forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

fetch.rs71 lines, 1.7 KiBHistoryRawDownload
1use std::{
2 collections::HashMap,
3 sync::{Arc, Mutex},
4};
5
6use common::open::Blob;
7use tokio::sync::{Semaphore, SemaphorePermit, oneshot};
8
9use super::{Fail, link};
10
11const PARALLEL_FETCHES: usize = 6;
12
13type Waiter = oneshot::Sender<Result<Arc<Vec<u8>>, Fail>>;
14
15pub(super) struct Fetches {
16 permits: Semaphore,
17 waiting: Mutex<HashMap<Blob, Vec<Waiter>>>,
18}
19
20impl Default for Fetches {
21 fn default() -> Self {
22 Self {
23 permits: Semaphore::new(PARALLEL_FETCHES),
24 waiting: Mutex::default(),
25 }
26 }
27}
28
29impl Fetches {
30 pub(super) async fn permit(&self) -> SemaphorePermit<'_> {
31 self.permits
32 .acquire()
33 .await
34 .expect("semaphore never closes")
35 }
36
37 pub(super) async fn memory(
38 &self,
39 connection: &quinn::Connection,
40 blob: Blob,
41 ) -> Result<Vec<u8>, Fail> {
42 let (sender, receiver) = oneshot::channel();
43 let leader = {
44 let mut waiting = self.waiting.lock().unwrap();
45 let senders = waiting.entry(blob.clone()).or_default();
46 senders.push(sender);
47 senders.len() == 1
48 };
49
50 if leader {
51 let result = {
52 let _permit = self.permit().await;
53 link::download(connection, &blob).await
54 }
55 .map(Arc::new);
56 let senders = self
57 .waiting
58 .lock()
59 .unwrap()
60 .remove(&blob)
61 .unwrap_or_default();
62 for sender in senders {
63 let _ = sender.send(result.clone());
64 }
65 }
66
67 let bytes = receiver.await.map_err(|_| Fail::Offline)??;
68
69 Ok((*bytes).clone())
70 }
71}